Reading ints from a txt file and storing to an array

arrays, file, java

Solution

You're printing out the virtual memory address of the array instead of the actual array items:

You can print out the actual array items, one by one, like this:

// This construct is called a for-each loop
for(int item: integers) {
   System.out.println(item);
}

@akuhn points out correctly that Java has a built in helper for this:

System.out.println(Arrays.toString(integers));

Note that you'll need to add:

import java.util.Arrays

in your imports for this to work.

Problem

I am trying to read integers from a text file and store them into an array. The text file reads: ``` 4 -9 -5 4 8 25 10 0 -1 4 3 -2 -1 10 8 5 8 ``` Yet when I run my code I get `[I@41616dd6` in the console window... ``` public static void main(String[] args) throws IOException { FileReader file = new FileReader("Integers.txt"); int[] integers = new int [100]; int i=0; try { Scanner input = new Scanner(file); while(input.hasNext()) { integers[i] = input.nextInt(); i++; } input.close(); } catch(Exception e) { e.printStackTrace(); } System.out.println(integers); } ```

Original source