• Post Reply Bookmark Topic Watch Topic
  • New Topic

Scanning next line of input without advancing past line  RSS feed

 
W Yuen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
I'm doing an assignment for uni and have come across a small hiccup.
What I'm trying to do is scan in a text file and read "commands" for it line by line, e.g:
Student Mary 12345 19
Student Joe 12346 19
Change Joe 19 20
Change Mary 19 20

So that lines that begin with the word "Student" indicate that I should create a new student file with that name, student ID, and age.
"Change" indicates that I should be changing the specified student's current age to the new age etc.

What I'm currently doing is something along the lines of this:

The problem I'm having is that every second line seems to be getting skipped (because I'm calling nextLine() so much?) but I can't think of a way to "peek" at the first word of each line without advancing past it. Is there any way of doing this?
Thank you for any help.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
W Yuen wrote:The problem I'm having is that every second line seems to be getting skipped (because I'm calling nextLine() so much?) but I can't think of a way to "peek" at the first word of each line without advancing past it. Is there any way of doing this?

Sure. Just use your 'line' variable rather than nextLine().
ie;
1. Read the nextLine() and put it in 'line'.
2. Do (AND check) everything you need to from 'line' until you're done with it.
3. Go back to 1.

Try it out. If you get really stuck, come back.

Winston
 
W Yuen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That works, thanks! Can't believe I didn't think of such a simple solution. Thanks again
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

There are several ways you can achieve that; you can use next() followed by nextLine() repeatedly, and various if‑elses. You can use nextLine and String#split. You can even use Strings as cases in a switch statementThe whiles you showed in your post will not work; you need 1 while with if or switch inside.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!