0

So I have an array and trying to print what was input to the scanner. I'm trying to print the matrix that was input. Heres the code, what am I doing wrong here? I tried to print just graph, doesn't work.

/** Accept number of vertices **/
    System.out.println("Enter number of vertices\n");
    int V = input.nextInt();

    /** get graph **/
    System.out.println("\nEnter matrix\n");
    int[][] graph = new int[V][V];
    for (int i = 0; i < V; i++)
        for (int j = 0; j < V; j++)
            graph[i][j] = input.nextInt();
            System.out.print(graph);
chatslayer
  • 47
  • 3
  • are you purposely trying to print the graph after each input from the user? or are you trying to print it out once when all the inputs have been received? – RAZ_Muh_Taz Oct 31 '16 at 20:54
  • 1
    @RAZ_Muh_Taz He's just printing it at the end. Although the `System.out.println(graph);` is indented, it isn't part of the for loops because the for loops have no curly braces. – Asaph Oct 31 '16 at 20:56
  • 1
    oh ok, that's right. the indentation and no curly braces were messing with my head... thanks for the clarification @Asaph – RAZ_Muh_Taz Oct 31 '16 at 20:58

3 Answers3

0

You can print the contents of an array using the Arrays.toString() method but it doesn't work for multidimensional arrays, so for a 2 dimensional array, you'll need to loop through the elements in the first dimension. Like this:

for (int[] g : graph) {
    System.out.println(Arrays.toString(g));
}
Asaph
  • 159,146
  • 25
  • 197
  • 199
0

Printing arrays by simply passing it into System.out.print will print the array's hashcode. See this.

What you want to do is: System.out.println(Arrays.deepToString(graph));

Arrays.toString(...) will work for single dimensional arrays.

Arrays.deepToString(...) will work for more complex arrays.

Community
  • 1
  • 1
pushkin
  • 9,575
  • 15
  • 51
  • 95
0

Because when you try to print graph, you are actually printing a reference to an array object (If I am correct).

Also, for variables (like "V") you should use small caps

Instead of printing a graph, do this:

 for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                System.out.print(graph[i][j]);
            }
            System.out.println();
        }
lmilunovic
  • 191
  • 1
  • 10