Bocky
Bocky

Reputation: 483

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.

Upvotes: 0

Views: 61

Answers (4)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22224

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

Upvotes: 1

Tefek
Tefek

Reputation: 162

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.

Upvotes: 0

Aaron
Aaron

Reputation: 24802

Actually you're reading the first integer of each line, because you are looping on lines but not on their content : you just check if the first token on the line is an int, read it, and go on to the next line.

Upvotes: 1

Joel Min
Joel Min

Reputation: 3457

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.

Upvotes: 0

Related Questions