简体   繁体   English

使用扫描仪从文本文件读取信息

[英]reading info using scanner from text file

I am facing this problem reading info from file. 我面临着从文件读取信息的问题。 So i have this text file with integers that I want to read and add into my ArrayList. 所以我有这个文本文件,它带有要读取的整数并将其添加到ArrayList中。 My problem now is that scanner only seems to read the first 2 lines instead of the entire file. 我现在的问题是扫描仪似乎只读取前两行,而不是读取整个文件。

My Text file: 我的文本文件:

6
0 4 10 0 0 2
4 0 5 0 0 7
10 5 0 4 0 0
0 0 4 0 3 8
0 0 0 3 0 6
2 7 0 8 6 0
2 5

And this is my code: 这是我的代码:

FileReader reader = new FileReader(inputFileName);
Scanner in = new Scanner(reader);

// read in the data here
while(in.hasNextLine()){
    if(in.hasNextInt())
        alist.add(in.nextInt());
    in.nextLine();
}

This is my output: 6 0 4 10 0 0 2 2 这是我的输出: 6 0 4 10 0 0 2 2

Hopefully somebody can me out with this. 希望有人可以帮我这个忙。 I tried storing everything in string and reading from there but i ended up with everything in single digits. 我尝试将所有内容存储在字符串中并从那里读取,但最终所有内容都以一位数字表示。

实际上,您正在读取每行的第一个整数,因为要在行上循环而不是在它们的内容上循环:您只需检查行上的第一个标记是否为int,然后读取它,然后继续下一行即可。

You should try this to read all the integers 您应该尝试读取所有整数

while(in.hasNextInt()){
    alist.add(in.nextInt());
}

When you say in.nextLine(); 当你说in.nextLine(); in your code it will get a new line. 在您的代码中它将换行。 So in the next iteration it will only scan the first integer in the line. 因此,在下一次迭代中,它将仅扫描该行中的第一个整数。 But with hasNextInt nextInt pair it will get integers skipping whitespace (space and new lines) and stop when it reaches the end of file 但是使用hasNextInt nextInt对时,它将获得跳过空格(空格和hasNextInt行)的整数,并在到达文件末尾时停止

Try this: 尝试这个:

FileReader reader = new FileReader(inputFileName);
Scanner in = new Scanner(reader);

// read in the data here
while(in.hasNext()){
    alist.add(in.nextInt());
}

You were having issue because of in.nextLine(); 您因为in.nextLine();而遇到问题in.nextLine(); that you called in the end of the while loop. 在while循环结束时调用的代码。 This will call in the next line, which make you skip lines. 这将在下一行中调用,使您跳过行。

if(in.hasNextInt())
    alist.add(in.nextInt());

Replace with 用。。。来代替

while(in.hasNextInt())
{
    alist.add(in.nextInt());
}

Because you read int from each line only once. 因为您从每一行读取int仅一次。

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

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