Evan
Evan

Reputation: 880

Trouble reading next int

(original question, already answered)

I want a program to read integers from a text file. The data file looks like this:

5 4
3 5
4 5
3 2

The first number of each row is the par, and the second number is the score. Because 5 - 4 = 1, the score is one under par (which is a birdie). My code for the first line:

    in = new Scanner (dataFile);
    System.out.println("Golf Scores: ");                                                
    String line1 = in.nextLine();       
    System.out.println("Score 1: " + line1);
    int par1 = in.nextInt();
    System.out.println("Par is: " + par1);

When I run it, I get this:

Golf Scores:

Score 1: 5 4

Par is: 3

So the par and score shows up correctly. However, the displayed par shows the par of the next line from the text file. I want it to show "5" again. I tried putting the in.nextInt before the in.nextLine, but when I tried that I got this

Golf Scores:

Score 1: 4

Par is: 5

Also please let me know if I need to add anything to explain my question better.

Upvotes: 0

Views: 245

Answers (3)

Java Devil
Java Devil

Reputation: 10969

You could read the line the split it like so

String line1 = in.nextLine();       
String[] parScore = line.split(" ");
System.out.println("Score 1: " + parScore[1]);
System.out.println("Par is: " + parScore[0]);

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53545

You shouldn't care if it's an int (although it's always an int - in your case) so you don't have to bother using nextInt():

String line = in.nextLine();    
String[] nums = line.split(" ");
System.out.println("score: " + nums[0]/*par*/ + " " + nums[1]/*score*/);
System.out.println("par is:" + nums[0]);

Upvotes: 3

arshajii
arshajii

Reputation: 129547

You can't "rewind" the scanner, once you've read the line, it's gone and you can't read from it again. You can try something like this:

int par = in.nextInt();
int score = in.nextInt();

System.out.println("Score: " + par + " " + score);
System.out.println("Par is:" + par);

Here, we're reading and storing the two integers separately to begin with, and displaying them just after.

Upvotes: 5

Related Questions