• Post Reply Bookmark Topic Watch Topic
  • New Topic

Scanner not working...  RSS feed

 
Sergey Brs
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Help me to solve this problem. I wrote a piece of code:

When i run it i get:

Enter number of students:
1
Enter students full name:
Enter students exam score:

The problem is, i cant enter "full name", program is just jumping to the next step "exam score". Don`t know how to solve this.
Thanks in advance.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sergey. Welcome to the Ranch!

I'm not certain, because it relates to the code just before this that we can't see, but here's what I think is happening.

- It asks for the number of students. You enter 1 and press return.
- Then you're using nextInt() to get the number? That will consume the 1, but it won't consume the carriage return.
- So when you then use nextLine(), there is still a return waiting to be read. So the Scanner reads that immediately and sets the student name to be blank.

If you're entering each number on a different line, you need to call nextLine() after you've called nextInt() each time to move the Scanner on.
 
Sergey Brs
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Matthew, it helped.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That problem is poorly described in the books, and lots of people get caught out like that. Look here and here, but read the following posts because I made a mistake.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome again
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!