java.util.Scanner does not return to Prompt

那年仲夏 提交于 2020-01-05 01:25:08

问题


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?


回答1:


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.



回答2:


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();
    }
}



回答3:


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();
    }
}


来源:https://stackoverflow.com/questions/7107432/java-util-scanner-does-not-return-to-prompt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!