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:
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"?
Edit: Be aware that foundCount
is the total number of elements found up until now, as it is never reset to zero. Was this intended?
Don't you agree that this code is easier to read and more concise? (Note: efficiency is the same as your code)
int[][] nums = {{1,1,2},{3,4},{5},{6,7,8},{9,1,1}};
int foundCount = 0;
for(int[] inner : nums){
for(int i : inner){
if (i == 1){
foundCount++;
}
}
System.out.println("Searched " + inner.length +
" elements, and found \'number one\' a total of " + foundCount + " times..");
}
Output:
Searched 3 elements, and found 'number one' a total of 2 times..
Searched 2 elements, and found 'number one' a total of 2 times..
Searched 1 elements, and found 'number one' a total of 2 times..
Searched 3 elements, and found 'number one' a total of 2 times..
Searched 3 elements, and found 'number one' a total of 4 times..
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments