Java Reference
In-Depth Information
< Day Day Up >
Puzzle 42: Thrown for a Loop
The following program loops through a sequence of int arrays and keeps track of how many of the
arrays satisfy a certain property. What does the program print?
public class Loop {
public static void main(String[] args) {
int[][] tests = { { 6, 5, 4, 3, 2, 1 }, { 1, 2 },
{ 1, 2, 3 }, { 1, 2, 3, 4 }, { 1 } };
int successCount = 0;
try {
int i = 0;
while (true) {
if (thirdElementIsThree(tests[i++]))
successCount++;
}
} catch (ArrayIndexOutOfBoundsException e) {
// No more tests to process
}
System.out.println(successCount);
}
private static boolean thirdElementIsThree(int[] a) {
return a.length >= 3 & a[2] == 3;
}
 
 
Search WWH ::




Custom Search