Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading ints from a txt file and storing to an array

Tags:

java

arrays

file

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);
    }
like image 256
user1877918 Avatar asked Dec 26 '22 13:12

user1877918


2 Answers

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.

like image 68
Randall Hunt Avatar answered Dec 29 '22 12:12

Randall Hunt


Unfortunately, Java’s designers missed to add a proper string representations for arrays.

Instead use

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

You need to import java.util.Arrays; to make this work.

like image 44
akuhn Avatar answered Dec 29 '22 11:12

akuhn