change array logic in java

Viewed 69

How can I change the following code so it prints out:

123
123
123

instead?

public class A4SXYY {
    public static void main(String[] args) {
        int[][] a2 = new int[3][3];
        for (int i = 0; i < a2.length; i++) {
            for (int j = 0; j < a2[i].length; j++) {
                a2[i][j] = i + 1;
                System.out.print(" " + a2[i][j]);
            }
            System.out.println("");
        }
    }
}
2 Answers
public static void main(String[] args) {
    int[][] a2 = new int[3][3];
    for (int i = 0; i < a2.length; i++) {
        for (int j = 0; j < a2[i].length; j++) {
            a2[i][j] = j + 1;
            System.out.print("" + a2[i][j]);
        }
        System.out.println("");
    }
}

123

public static void main(String[] args) {
    int[][] a2 = new int[3][3];
    for (int i = 0; i < a2.length; i++) {
        for (int j = 0; j < a2[i].length; j++) {
            a2[i][j] = 3 - j;
            System.out.print("" + a2[i][j]);
        }
        System.out.println("");
    }
}

321

The only issue you have is in the line where you assign a value to the array. You use the are using i+1 and should be using j+1. See corrected code below:

public class A4SXYY{
    public static void main(String[] args){
        int[][] a2 = new int[3][3];
        for (int i=0; i<a2.length; i++){
            for (int j=0; j<a2[i].length; j++){
                a2[i][j] = j+1; //Use j instead of i
                System.out.print(" " + a2[i][j]);
            }
            System.out.println("");
        }
    }
}
Related