Workshop 1 Hacks
FRQ 2: Iteration over 2D arrays (Unit 4)
Situation: You are developing a game where you need to track player scores on a 2D grid representing levels and attempts.
(a) Explain the concept of iteration over a 2D array in Java. Provide an example scenario where iterating over a 2D array is useful in a programming task.
In Java, iterating over a 2D array involves traversing through each element of the array typically requires the use of nested loops, one for iterating over rows and another for iterating over columns. The first for loop in the format for (int i = 0; i < array2D.length; i++)
iterates through all the rows whereas the nested loop for (int j = 0; j < array2D[i].length; j++)
iterates through all the elements in that row (ie the columns).
(b) Code:
You need to implement a method calculateTotalScore that takes a 2D array scores of integers representing player scores and returns the sum of all the elements in the array. Write the method signature and the method implementation. Include comments to explain your code.
public class Main {
public static int calculateTotalScore (int[][] scores) {
int sum = 0; // keep track of the running total of the sum
for (int i = 0; i < scores.length; i++)
{
for (int j = 0; j < scores[i].length; j++)
{
sum += scores[i][j]; //iterate through each element and add it to the sum
}
}
return sum;
}
public static void main(String[] args) {
int[][] scores = { //test array
{1, 2, 3},
{3, 4, 5},
{5, 6, 7}
};
System.out.println(calculateTotalScore(scores));
}
}
Main.main(null);
36
FRQ 4: Math Class (Unit 2)
Situation: You are developing a scientific calculator application where users need to perform various mathematical operations.
(a) Discuss the purpose and utility of the Math class in Java programming. Provide examples of at least three methods provided by the Math class and explain their usage.
To do math functions.
Math.random gives a random float to get a random value
Math.pow raises a value to a power
Math.min finds the minimum of two numbers
(b) Code:
You need to implement a method calculateSquareRoot that takes a double number as input and returns its square root using the Math class. Write the method signature and the method implementation. Include comments to explain your code.
import java.lang.Math.*;
public class Main {
public static double calculateSquareRoot(double root) {
return Math.sqrt(root); //square root the number
}
public static void main (String[] args) {
System.out.println(calculateSquareRoot(5.4002));
}
}
Main.main(null);
2.3238330404742937