简体   繁体   中英

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. 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

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 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

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(); that you called in the end of the while loop. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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