简体   繁体   中英

Terminating a user input determined Scanner?

I wonder if someone could explain why the scanner keeps waiting on input? I have to stop the process on eclipse before the code block executes and I am unsure why the scanner will keep taking input all day . I expect to press enter and for the code to execute after entering X amount of numbers.

public static void main(String[] args){
    Scanner aScanner = new Scanner(System.in);  
    int sum = 0;
    System.out.println("Enter Ints : ");         
    while(aScanner.hasNextInt()){
        sum += aScanner.nextInt(); 
    }       
    System.out.println(sum);
}

if you want the program to take only X amount of numbers, you could have a counter and break the while loop after it has executed X number of times. Alternatively, you could also use a for loop to make things easier.

You could also use Ctrl+Z in eclipse to stop console from waiting for inputs.

The simplest way to solve it is:

  • Enter the "end of file" marker, by the combination Ctrl + z ( Ctrl + d in UNIX, if I'm not wrong).

Another way would be using a centinel value tu finish the while loop:

Scanner aScanner = new Scanner(System.in);
int sum = 0, input = 0;

System.out.println("Enter Ints (-999 to finish input): ");
while ((input = aScanner.nextInt()) != -999) {
    sum += input;
}
System.out.println(sum);

so the input will finish when the user enters -999 , of course you can change this value.

Note:

  • The last approach won't work if you expect any integer (including negatives and extrene values) as input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM