开发者

java.util.Scanner does not return to Prompt

开发者 https://www.devze.com 2023-03-29 04:04 出处:网络
import java.util.Scanner; class newClass { public static void main(String args[]) { Scanner s = new Scanner(System.in);
import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.开发者_运维问答hasNext()) {
            System.out.println(s.next());
        }
        s.close();
    }
}

This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?


This program does not return to prompt (I have been running it through the Terminal). Why is that?

Because s.hasNext() will block until further input is available and will only return false if it encounters end of stream.

From the docs:

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan.

On a unix system you can end the stream by typing Ctrl+D which correctly returns control to the prompt, (or terminate the whole program by typing Ctrl+C).

How can I correct it?

You can either

  • reserve some input string used for terminating the program, as suggested by JJ, or
  • you could rely on the user closing the input stream with Ctrl+D, or you could
  • enclose the loop in a try/catch and let another thread interrupt the main thread which then exits gracefully.
  • do System.in.close() programatically from another thread.


This is a reply to a comment above. Here, the application will quit when receiving "quit".

import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            String temp = s.next();
            if(temp.trim().equals("quit"))
                System.exit(0);
            System.out.println(s.next());
        }
        s.close();
    }
}


The Scanner will block waiting for input from System.in (standard input). You have to press Ctrl+C to exit the program, close the Input stream by pressing Ctrl+D or give the loop an exit condition (like typing "quit"), here is how you could do that:

import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            String nextVal = s.next();
            if (nextVal.equalsIgnoreCase("quit")) { break; }
            System.out.println(nextVal);
        }
        s.close();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消