从txt文件读取int并存储到数组

use*_*918 4 java arrays file

我试图从文本文件中读取整数并将它们存储到数组中.文本文件如下:

4
-9
-5
4
8
25
10
0
-1
4
3
-2
-1
10
8
5
8
Run Code Online (Sandbox Code Playgroud)

然而,当我运行我的代码时,我进入[I@41616dd6控制台窗口......

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);
    }
Run Code Online (Sandbox Code Playgroud)

Ran*_*unt 5

您正在打印出数组的虚拟内存地址而不是实际的数组项:

您可以逐个打印出实际的数组项,如下所示:

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

@akuhn正确地指出Java有一个内置的帮助:

System.out.println(Arrays.toString(integers));
Run Code Online (Sandbox Code Playgroud)

请注意,您需要添加:

import java.util.Arrays
Run Code Online (Sandbox Code Playgroud)

在你的导入中为此工作.