Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Array, output is no where near correct

import java.util.Scanner;

public class Maze {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int rows = 0;
        int cols = 0;
        String arrayLine = "";
        int counter = 0;

        rows = sc.nextInt();
        cols = sc.nextInt();
        arrayLine = sc.next();

        char[][] array = new char[rows][cols];

        for(int r=0; r<rows; r++){
            for (int c=0; c<cols; c++){
                array[r][c] = arrayLine.charAt(counter);
                counter ++;
            }
        }

        System.out.println(array);
        System.out.println();
    }
}

The document I'm bringing in the information from is:

8
7
000000011111S0000000110101111010101100010110111011010E00

The output I'm getting it when i run it is [[C@252f0999

Help please, I'm just starting to learn java!

like image 438
Jonathan Murray Avatar asked Jan 14 '23 09:01

Jonathan Murray


2 Answers

array is a special kind of object, it doesn't have an implicit toString() which manages pretty printing of the content of the array, what happens is that the object is represented by the standard representation for objects which is its hashcode.

You should use Arrays.toString():

for (int i = 0; i < array.length; ++i)
  System.out.println(Arrays.toString(array[i]));

Mind that you can't directly write Arrays.toString(array) because, as stated in documentation:

If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.

like image 137
Jack Avatar answered Jan 21 '23 12:01

Jack


When you call println() on an object, Java returns the location of the resource by default (that's what C@252.... is). You want to call

System.out.println(Arrays.deepToString(array) 

to display the data in the array.

like image 29
drew moore Avatar answered Jan 21 '23 12:01

drew moore