如何停止等待用户输入? [英] How to stop waiting for user input?

查看:138
本文介绍了如何停止等待用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个程序来询问乘法,我想设置一个计时器来强制该人在给定时间内给出答案:

I'm building a programm to ask multiplication and I want to set up a timer to force the person to give its answer in a given time :


  1. 如果此人在计时器结束前回答:转到下一个乘法

  2. 如果计时器到达终点,则停止等待用户输入:转到下一个乘法

目前,案例 1 可以完成,但 2 不是,我正在考虑一种方法来返回; 从方法内部就像一个Thread或者什么东西,我不知道怎么样

For the moment, case 1 can be done, but 2 not, I was thinking about a way to return; from the method within like a Thread or something, bu I don't know how

所以我遇到问题,如果扫描仪打开,等待输入,如何停止?我已经尝试将它放在一个Thread和 interrupt()中,或者使用 boolean 作为标志,但它没有' t停止扫描仪

So I'm facing a problem, if a Scanner is open, waiting for input, how to stop it ? I've tried putting it in a Thread and interrupt() it or using boolean as flags, but it doesn't stop the Scanner

class Multiplication extends Calcul {    
    Multiplication() {  super((nb1, nb2) -> nb1 * nb2); }   
    @Override
    public String toString() {  return getNb1() + "*" + getNb2(); }
}


abstract class Calcul {

    private int nb1, nb2;
    private boolean valid;
    private boolean inTime = true;
    private boolean answered = false;
    private BiFunction<Integer, Integer, Integer> function;

    Calcul(BiFunction<Integer, Integer, Integer> f) {
        this.nb1 = new Random().nextInt(11);
        this.nb2 = new Random().nextInt(11);
        this.function = f;
    }

    void start() {
        Scanner sc = new Scanner(System.in);
        System.out.println("What much is " + this + " ?");

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!answered) {
                    inTime = false;
                }
            }
        }, 5 * 1000);

        int answer = Integer.parseInt(sc.nextLine());
        if (inTime) {
            checkAnswer(answer);
            timer.cancel();
        }
    }    

    private void checkAnswer(int answer) {
        System.out.println("You said " + answer);
        valid = (function.apply(nb1, nb2) == answer) && inTime;
        answered = true;
    }

    int getNb1() {   return nb1;  }    
    int getNb2() {   return nb2;  }    
    boolean isValid() { return valid; }

     public static void main(String[] args) {
         List<Calcul> l = Arrays.asList(new Multiplication(), new Multiplication(), new Multiplication());
         l.forEach(Calcul::start);
}
}


推荐答案

你可以检查 System.in.available()> 0 查看是否有要读取的行。只有在返回true时才调用 sc.nextLine()来实际接收输入。

You can check for System.in.available() > 0 to see if there is a line to read. Only if this returns true call the sc.nextLine() to actually receive the input.

示例:

Scanner sc = new Scanner(System.in);

long sTime = System.currentTimeMillis();
while (System.currentTimeMillis() - sTime < 5000)
{
    if (System.in.available() > 0)
    {
        System.out.println(sc.nextLine());
    }
}

sc.close();

如果有东西需要阅读并再打印出来,这将从控制台读取5秒钟。 注意:实际使用时,你可能会在循环中抛出 sleep ,而不是拥抱许多系统资源。

This reads from the console for 5 seconds if there is something to read and just prints it out again. Note: When actually using this you would probably throw a sleep in the loop to not hug to many system resources.

请注意,这是一个可以工作解决方案: available()往往是一个不可靠的方法,做一些估计可能是错误的。我可能不会在时间要求严格的系统等中依赖它。

Please note that this is a can work solution: available() tends to be an unreliable method that does some estimation and can be in the wrong. I would probably not rely on it in a time-critical system, etc.

此外,为了进一步扩展,这种方法依赖于控制台以的方式工作控制台工作(换句话说:我所知道的所有控制台):只有当用户输入换行符时(例如按下输入),该行实际上被赋予 System.in 处理。否则只有一个字符被输入时, available()将返回true。

Also to further expand, this approach relies on the console to work the way most consoles work (in other words: All consoles that I know of): Only when the user enters a newline (by e.g. pressing enter) the line is actually given to System.in to process. Else available() would already return true when only one character gets typed.

这篇关于如何停止等待用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆