簡體   English   中英

如何阻止 Java 掃描器接受輸入

[英]How to stop Java Scanner from accepting input

所以,我正在開發一個從命令行運行的測驗程序,測驗有時間限制。 我想做的是在用戶時間結束時立即停止測驗,即使他們正在回答問題。 我正在使用 Java 的 Scanner 來獲取用戶的輸入,所以我基本上想告訴 Scanner object 終止,即使它正在接受輸入。

現在,我知道我可以在事后追溯懲罰超時的用戶,但我只是希望在超過時間限制后終止測驗。 例如,有沒有辦法用多線程來做到這一點?

Java Scanner正在使用阻塞操作。 不可能阻止它。 甚至沒有使用Thread.interrupt();

但是,您可以使用BufferedLineReader讀取並能夠停止該線程。 這不是一個簡潔的解決方案,因為它涉及暫停短時間(否則它會使用100%的CPU),但它確實有效。

public static class ConsoleInputReadTask {
    private final AtomicBoolean stop = new AtomicBoolean();

    public void stop() {
        stop.set(true);
    }

    public String requestInput() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("ConsoleInputReadTask run() called.");
        String input;
        do {
            System.out.println("Please type something: ");
            try {
                // wait until we have data to complete a readLine()
                while (!br.ready() && !stop.get()) {
                    Thread.sleep(200);
                }
                input = br.readLine();
            } catch (InterruptedException e) {
                System.out.println("ConsoleInputReadTask() cancelled");
                return null;
            }
        } while ("".equals(input));
        System.out.println("Thank You for providing input!");
        return input;
    }
}

public static void main(String[] args) {
    final Thread scannerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String string = new ConsoleInputReadTask().requestInput();
                System.out.println("Input: " + string);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
    scannerThread.start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            scannerThread.interrupt();
        }
    }).start();
 }

我受夠了看着人們談論編程並提供不了解編程的糟糕解決方案。 最糟糕的是,談論像Java™這樣靈活的語言。

這是你的解決方案,人們:


    public static void main(String[] args) throws IOException
    {
        Scanner sc = new Scanner(new BufferedInputStream(System.in), "UTF-8");
        String item;
        
        while (true)
        {
            System.out.print("Give me some input:\t");
            if (!(item = sc.nextLine()).equals(""))
                System.out.println("\nYour Input was:\t" + item);
            else
                break;
        }
        
        System.out.println("Goodbye, see you again!");
    }

來自Java™ Programming 大師(本人多年經驗)8-|

示例 Output:

Give me some input: Your

Your Input was: Your
Give me some input: Programming

Your Input was: Programming
Give me some input: Knowledge

Your Input was: Knowledge
Give me some input: Sucks

Your Input was: Sucks
Give me some input: !!!

Your Input was: !!!
Give me some input: In the next line I'll just type ENTER so that my input is recognized as empty ;-)

Your Input was: In the next line I'll just type ENTER so that my input is recognized as empty ;-)
Give me some input: 
Goodbye, see you again!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM