Reputation:
I just started programming java, and I'm new to English please try to understand my sentence.
I tried to add a fifth number inside the the array. The for loop is not reading number 99 inside the array. I don't want table.length then add one , i want to add as many number as i want in the array and without change the for loop. Is there a code to find how many numbers are in a box(the first array box)?
int[][] table = { { 12, 0, 0, 0 ,99}, { 0, 0, 0, 0, 99}, { 0, 0, 0, 0, 99} };
int max = Integer.MIN_VALUE;
for (int i = 0; i < table.length; i++) {
for (int k = 0; k <= table.length; k++) {
if (table[i][k] >= max) {
max = table[i][k];
}
}
}
System.out.println(max);
int min = Integer.MAX_VALUE;
for (int i = 0; i < table.length; i++) {
for (int k = 0; k <= table.length; k++) {
if (table[i][k] <= min) {
min = table[i][k];
}
}
}
System.out.println(min);
Upvotes: 2
Views: 324
Reputation: 4730
Hello and welcome to the fun world of Java :-D
The problem is that your "inner" arrays have length 5, but the outer array is of length 3. You are re-using table.length
for both loops. For the inner loop try
for (int k = 0; k < table[i].length; k++) { // Iterate across all the inner arrays
if (table[i][k] >= max) {
max = table[i][k];
}
}
You are also iterating the table twice, once to find the max value and once to find the min. This is not too expensive with only a few elements, but imagine if you had millions. You can combine both checks in one pass of table. You can also reduce the amount of code by setting a variable for the value in the table. It means you only need to access the array once. Not much of a saving CPU wise, but it makes the code a little easier on the eye.
int[][] table = { { 12, 0, 0, 0 ,99}, { 0, 0, 0, 0, 99}, { 0, 0, 0, 0, 99} };
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < table.length; i++) {
for (int k = 0; k < table[i].length; k++) {
int val = table[i][k];
if (val > max) {
max = val;
}
if (val < min) {
min = val;
}
}
}
System.out.println(max);
System.out.println(min);
Upvotes: 5
Reputation: 21
What Spangen has mentioned is absolutely right with a small correction that you should iterate within "inner" arrays with "<" rather then "<=" which will break the array index.
for (int k = 0; k < table[i].length; k++) { // Iterate across all the inner array
if (table[i][k] >= max) {
max = table[i][k];
}
}
If you are trying to learn array in general than this if fine, else there are better ways to do this in Java 8 as mentioned here Finding minimum and maximum in Java 2D array
Upvotes: 2