简体   繁体   中英

Java scanner - can't read user input

I want to read user input like: 11 12 13 14 15 16

Scanner sc = new Scanner(System.in);
    while(sc.hasNext()){
        System.out.println(sc.next());

    }
    System.out.println("Test");

but it newer goes out of while loop and prints "Test". How could i read that input?

The method hasNext() works like this:

  • If it sees the end of the file, it returns false;
  • If it sees another valid, non-whitespace input, it returns true;
  • If neither of the above is true, it waits for the next input the user is going to enter, and doesn't return until he does.

Usually, if you use Scanner for files, such a loop will work correctly, because a file has a definite end, and it usually doesn't get stuck waiting for more input.

But when you are working with console input ( System.in , not redirected), then usually the user does not send the end-of-file signal. He just presses Return , and so, hasNext() sits and waits to see if the user will enter more input on the next line and so on.

There are two general ways to deal with this:

  • The user has to actually terminate the input. After you finish entering all your numbers and press Return , you also need to send the end-of-file sequence, which is usually ctrl D or ctrl Z .

    If you do that, you will not be able to enter any more input to that program.

  • The program tells the user to enter some particular value that will tell it that the input is over. For example, the string "DONE". When you do that, you have to change the loop to something like:

     String nextInput; while( sc.hasNext() && ! (nextInput = sc.next()).equals( "DONE" ) ){ System.out.println(nextInput); } 

You can break the loop depending whether you want to quit or not Eg

 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String next = sc.next();

            if (next.equals("q")) { //if user press q then break the loop
                break;
            }
            System.out.println(next);

        }
        System.out.println("Test");
    }

Use api like:

while(sc.hasNextInt()){
    int aba= sc.nextInt();
    if (aba == 0) {//or even non numeric value here would let this loop exit
        break;
    }
}

So you need to enter 0 or even in other way enter non numeric value inorder to come out of loop. nextLine method will read whole line just once and then you will need to parse it and then convert to integer so it's good to use sc.nextInt which will do the work for you.

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