By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,945 Members | 1,692 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,945 IT Pros & Developers. It's quick & easy.

hasNextInt() reading problem

P: 1

I have a problem while reading 3 integers in each line of which I don't know the number of. The problem I have is with the last line of integers. It simply refuses to print out and the program doesn't stop running. Here is my code:
Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  4. public class Restaurant {
  5.     public static void main(String[] args){
  6.         Scanner sc = new Scanner(;
  8.         int money = sc.nextInt();
  10.         while(sc.hasNextInt()){
  11.             int price = sc.nextInt();
  12.             int quantity = sc.nextInt();
  13.             int wine = sc.nextInt();
  15.             System.out.println(price+" "+quantity+" "+wine);
  17.         }        
  18.     }
  19. }

I test it by pasting the following numbers
Expand|Select|Wrap|Line Numbers
  1. 500
  2. 30 5 0
  3. 30 6 1
  4. 15 5 1
  5. 20 7 0
  6. 50 4 1
but it doesn't print out 50 4 1...

What could be the problem?
Aug 18 '15 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 785
The integers you type are only put into the input channel when you press CR (Return-Key). The reason is that a human may make typing errors that he wants to correct before submitting. So the input channel is blocked until you press CR. That's why it does not print the last line, it waits for you to press CR. And it does not matter if you put one or more integers on an input line.
How should the program know when you are finished? If the input comes from a file, then there is a file end, but if the user enters characters there is no end, the user can keep adding lines as long as he wants. The program cannot read the mind of the user that he is finished with entering after a specific number of lines. That's why hasNextInt() will be never false and the loop goes forever. Only if you enter something different than numbers and spaces (let's say a letter), then hasNextInt() will be false and the loop ends.
Usually in programs like that, you give an instruction to the user like "enter 'end' to finish program".
Aug 18 '15 #2

Post your reply

Sign in to post your reply or Sign up for a free account.