Adam Calcanes Adam Calcanes - 1 month ago 5
Java Question

Printing a 2d array in Java like a table

I'd like to print an inputed 2-dimensional array like a table
i.e if for some reason they put in all 1s...

1 1 1 1

1 1 1 1

1 1 1 1

1 1 1 1


Just like so above but in the console on Java eclipse, no fancy buttons and GUI's but in the console, here is what I have....

import java.util.Scanner;
public class Client {
public static void main(String[] args){
Scanner input = new Scanner(System.in);

int[][] table = new int[4][4];
for (int i=0; i < table.length; i++) {
for (int j=0; j < table.length; j++) {
System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
System.out.print(table[i][j] + " ");
}
System.out.println();
}
System.out.println(table);
}
}


And this is what I get when I input everything and the console terminates:

Enter a number.

1

1 Enter a number.

1

1 Enter a number.

1

1 Enter a number.

1

1

[[I@3fa1732d

Answer

You need to print out the array separately from entering the number. So you can do something like this:

public class PrintArray {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int[][] table = new int[4][4];
        for (int i = 0; i < table.length; i++) {
            for (int j = 0; j < table.length; j++) {
                // System.out.println("Enter a number.");
                int x = input.nextInt();
                table[i][j] = x;
            }
            //System.out.println();
        }
        // System.out.println(table);

        for (int i = 0; i < table.length; i++) {
            for (int j = 0; j < table[i].length; j++) {
                System.out.print(table[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Comments