0

I have to read from an external file, a list of numbers and insert them into their own array for being positive or negative. The scanner reads the numbers just fine, but when it inserts them into an array is where it goes wrong. As you can see below is my code, and the output. What is in the file is printed in the output, but when I ask it to print the arrays, it's that jumbled mess of letters/numbers/symbols. Can anyone help me fix it?

public class Numbers {
    public static void main(String[] args) throws IOException {
        Scanner reader = new Scanner(new FileInputStream("First.dat"));
        int Positive[] = new int[20];
        int Negative[] = new int[20];
        int X = 0;
        int Y = 0;
        while (reader.hasNextInt()) {
            int Start = reader.nextInt();
            System.out.println(Start);
            if (Start < 0) {
                Negative[X] = Start;
                X += 1;
            }
            if (Start > 0) {
                Positive[Y] = Start;
                Y += 1;
            }

        }
        System.out.println(Positive + "  " + Negative);
    }
}

Output:

3
66
54
-8
22
-16
-56
19
21
34
-34
-22
-55
-3
-55
-76
64
55
9
39
54
33
-45
[I@1b41650  [I@24e11c
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Max.C
  • 25
  • 5

2 Answers2

6

You are seeing the results of converting an array directly to a String. Arrays are objects too, but they don't override Object's toString() method, which is responsible for the "jumbled mess".

In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Explicitly convert the contents of the array to a String with Arrays.toString.

System.out.println(Arrays.toString(Positive) + "  " + Arrays.toString(Negative));
Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

What you're seeing is the object reference of the array. To print out the contents of the array as you're obviously expecting use Arrays.toString()

evanchooly
  • 6,102
  • 1
  • 16
  • 23