hasNextInt() reading problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ColEpsi
    New Member
    • Aug 2015
    • 1

    hasNextInt() reading problem

    Hello,

    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:
    Code:
    import java.util.Scanner;
    
    
    public class Restaurant {
    	public static void main(String[] args){
    		Scanner sc = new Scanner(System.in);
    		
    		int money = sc.nextInt();
    		
    		while(sc.hasNextInt()){
    			int price = sc.nextInt();
    			int quantity = sc.nextInt();
    			int wine = sc.nextInt();
    			
    			System.out.println(price+" "+quantity+" "+wine);
    			
    		}		
    	}
    }

    I test it by pasting the following numbers
    Code:
    500
    30 5 0
    30 6 1
    15 5 1
    20 7 0
    50 4 1
    but it doesn't print out 50 4 1...


    What could be the problem?
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    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".

    Comment

    Working...