Hellmud
Hellmud

Reputation: 49

Scanner array (n x n)

My code :

import java.util.Scanner;
class Test1 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int[][] num = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            System.out.print(num[i][j] + " ");
        System.out.println();
    }
}

the answer come out

0 0 0 
0 0 0 
0 0 0

but i want to make

1 0 0
0 1 0 
0 0 1

Upvotes: 0

Views: 48

Answers (1)

Shanu Gupta
Shanu Gupta

Reputation: 3807

As explain in the doc of Java, a int is initialized with the value 0. So when you only declare your array without setting specific value, it only contains 0. That's why your output is

0 0 0
0 0 0
0 0 0

You need to first initialize your array to put the value 1 in the wanted places. In your case you want to make an identity matrix, so put 1 in the places that have the same index for row and column (In the diagonal). This should look like this :

for (int i = 0; i < n; i++)
    num[i][i] = 1;

Place this initialization before printing the array, so the full code will look like :

Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++)
    num[i][i] = 1;
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++)
        System.out.print(num[i][j] + " ");
    System.out.println();

}

Upvotes: 1

Related Questions