The following code compiles and does what I require. It iterates through an int-based multidimensional array (called nums), and searches for all occurances of the value 1
. This program's output is shown below. There are three things to note:
- Regarding the "outer for" loop statement, I have used Java's comma operator to declare two additional variables.
- Also regarding this "outer for", I've used another comma operator in the "iteration section", to reset one of these additional variables.
- Regarding the "inner for", I've used another comma operator in the "iteration section" to increment this additional variable.
int[][] nums = {{1,1,2},{3,4},{5},{6,7,8},{9,1,1}};
for (int i=0, elsSearched=0, foundCount=0; i < nums.length; i++, elsSearched=0) {
for (int j=0; j < nums[i].length; j++, elsSearched++) {
if (nums[i][j] == 1) {
foundCount++;
}
}
System.out.println("Searched " + elsSearched +
" elements, and found \'number one\' a total of " + foundCount + " times..");
}
Program output:
Could this code be written more effeciently/elegantly?
My other query is about Java's "for each" loop. I tried rewritting the code above using the "for each" loop with the comma operator, but the code wouldn't compile. I quickly came to the obvious conclusion, but would the "for each" loop be better if the comma operator could be used with it, or would that just introduce "distracting clutter"?