简体   繁体   English

如何阻止 Java 扫描器接受输入

[英]How to stop Java Scanner from accepting input

So, I am working on a quiz taking program that works from the command line and the quizzes have time limits.所以,我正在开发一个从命令行运行的测验程序,测验有时间限制。 What I want to do, is to stop the quiz right when the user's time is up even if they're in the middle of answering a question.我想做的是在用户时间结束时立即停止测验,即使他们正在回答问题。 I am using Java's Scanner to get the user's input, so I want to essentially tell the Scanner object to terminate even if it's in the middle of accepting input.我正在使用 Java 的 Scanner 来获取用户的输入,所以我基本上想告诉 Scanner object 终止,即使它正在接受输入。

Now, I know that I can retroactively punish a user for going over time after the fact, but I simply want the quiz to terminate once the time limit has been exceeded.现在,我知道我可以在事后追溯惩罚超时的用户,但我只是希望在超过时间限制后终止测验。 Is there any way to do this with multithreading for example?例如,有没有办法用多线程来做到这一点?

A Java Scanner is using blocking operations. Java Scanner正在使用阻塞操作。 It is not possible to stop it. 不可能阻止它。 Not even using Thread.interrupt(); 甚至没有使用Thread.interrupt();

You can however read using a BufferedLineReader and be able to stop the thread. 但是,您可以使用BufferedLineReader读取并能够停止该线程。 It's not a neat solution, as it involves pausing for short moments (otherwise it would use 100 % CPU), but it does work. 这不是一个简洁的解决方案,因为它涉及暂停短时间(否则它会使用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();
 }

I fed up watching people talking about programming and providing with shitty solutions THAT have no understanding of programming.我受够了看着人们谈论编程并提供不了解编程的糟糕解决方案。 And the worst thing of all, talking shit about a such a flexible language as Java™ is.最糟糕的是,谈论像Java™这样灵活的语言。

Here is your solution, people:这是你的解决方案,人们:


    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!");
    }

From the master of Java™ Programming (with years of experience in my hands) 8-|来自Java™ Programming 大师(本人多年经验)8-|

Example Output:示例 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