Java 2 dimensional array value and for loop problems

TKperson 1 :

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);
Spangen :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112748&siteId=1