PRACTICE EXAM 2 SAMPLE ANSWERS 1. (a) total 1 1+ 1 = 2 2+ 2 = 4 4+ 4 = 8 8+ 8 = 16 16+16 = 32 32+32 = 64 64+64 = 128 > 100 exit loop prints 128 (b) result 4 8 16 32 64 128 <- skips over 100, infinite loop, never reaches the print statement and prints nothing (c) i sum 0 1 1 (0+1) 4 5 (1+4) 7 12 (5+7) 10 22 (12+10) 13 <- exit loop, prints 22 (d) i product 1 10 <- exit loop, prints 1 (e) str = "Carnegie", length = 8 i charAt(i) 1 a 3 n 5 g 7 e 9 <- exit loop, prints ange 2. (a) i j sum product 1 1 0 1 1 2 <- exit j-loop 1 2 0 1 1 2 3 3 <- exit j-loop 3 3 0 1 1 2 3 3 6 4 <- exit j-loop 18 4 <- exit i-loop prints 18 (b) i j sum product 0 1 1 1 1 2 exit j-loop 1 2 1 2 2 4 3 exit j-loop 4 3 1 5 2 7 3 10 4 exit j-loop 40 4 exit i-loop prints 40 (c) product = 1; int i = 1; while (i < 4) { int sum = 0; int j = 1; while (j <= i) { sum +=j; j++; } product *= sum; i++; } System.out.println(product); 3. (a) score = new int[30]; (b) for (int i = 0; i < 30; i++) { score[i] = (int) (Math.random() * 20) * 5 + 5; } (c) int max = score[0]; for (int i = 1; i < 30; i++) { if (score[i] > max) { max = score[i]; } } (d) Yes. It must be a static method because random is called on the class Math, not on an object of the Math class. 4. (a) public static int countOutliers(double[] data, double lower, double upper) { int count = 0; for (int i = 0; i < data.length; i++) { if ((data[i] < lower) ||_ (data[i] > upper)) { count = count + 1; } } return count; } (b) System.out.println("The number of outliers in pH is " + countOutliers(pH, 0.0, 14.0)); 5. public class DiceGame { public static void main(String[] args) { Die die1 = new Die(6); Die die2 = new Die(6); int score = 0; int numRolls = 1; while (score < 70 && numRolls <= 10) { die1.roll(); die2.roll(); if (die1.getFaceValue() == die2.getFaceValue()) [ score = score - 10; if (score < 0) { score = 0; } } else { score = score + die1.getFaceValue() + die2.getFaceValue(); } System.out.println("You rolled " + die1.getFaceValue() + " " + die2.getFaceValue() + ". Your score is " + score); } if (score >= 70 { System.out.println("WINNER"); } else { System.out.println("LOSER"); } } }