简体   繁体   English

如何读取一行中每个int的.txt文件并存储到数组中?

[英]How to read a .txt file for each int on a line & storing to array?

public class assignment2
{
    public static void main(String[] args) throws IOException 
    {
        // TODO Auto-generated method stub
        FileInputStream fstream = new FileInputStream("assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console
            System.out.println (strLine);
            String[] numbers = strLine.split(" ");
            System.out.print(numbers[1]);
        }
        //Close the input stream
        br.close();
    }
}

I expect that the code will print the String[] numbers as 1 0 10 我希望代码将String []数字打印为1 0 10

I get this result 00371010 我得到这个结果00371010

Please note that the input file is formatted as such: 请注意,输入文件的格式如下:

1 0 10 1 0 10

2 0 9 2 0 9

3 3 5 3 3 5

4 7 4 4 7 4

5 10 6 5 10 6

6 10 7 6 10 7

Just replace your line: 只需替换您的行:

System.out.print(numbers[1]);

With: 附:

for (int i = 0; i < numbers.length; i++)
    System.out.print(numbers[i] + " ");

System.out.println();

Let me know how it works. 让我知道它是如何工作的。

You need to modify the code by adding another loop like this: 您需要通过添加另一个循环来修改代码,如下所示:

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    FileInputStream fstream = new FileInputStream("assignment2.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    String strLine;

    //Read File Line By Line
    while ((strLine = br.readLine()) != null){
        // Print the content on the console
        System.out.println (strLine);
        String[] numbers = strLine.split(" ");
        for (String num : numbers){
            System.out.print(num + " ");
        }
        System.out.println("\n");
    }
    //Close the input stream
    br.close();
}

Because, numbers[1] will only print the value at index 1. 因为,numbers [1]仅将索引1上的值打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM