Java中超时的用户输入 [英] User input with a timeout in Java

查看:39
本文介绍了Java中超时的用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此功能构建命令行界面:如果用户插入输入(在本例中为整数)的时间超过 15 秒,则该函数会做出默认选择 (0).下面的代码是我到目前为止所写的,它可以正常工作.

I'm trying to build a Command Line Interface with this functionality: if the user takes more than 15 seconds to insert an input (an Integer in this case), the function makes a default choice (0). The code below is what I wrote so far and it works properly.

问题是我想添加一个新功能:如果用户写了一个错误的数字(<0 或 >range),控制台应该打印类似 (错误的选择,你必须在0 - "+ 范围);

The problem is that I wanna add a new functionality: if the user writes a wrong number (<0 or >range) the console should print something like ("Wrong choice, you have to pick an integer between 0 - "+ range);

然而,当控制台打印消息时,计时器应该仍在运行并在 15 秒后结束此循环,以防用户不断插入错​​误的数字.如果用户最终得到一个正确的数字,它应该立即打破循环.

However, while the console prints the message, the timer should still be running and end this loop after 15 seconds, in case the user keeps inserting wrong numbers. In case the user gets eventually a correct number, it should break the loop immediately.

这是我的代码,但我对如何添加功能没有明确的想法,因为我对 Future、Callable 和 Executor 功能比较陌生.如果有人对此有更多经验,我很乐意学习!

This is my code, but I don't have clear ideas on how to add the functionality because I'm relatively new to Future,Callable and Executor functionalities. If anyone has more experience on it I would be glad to learn!

private int getChoiceWithTimeout(int range){
       Callable<Integer> k = () -> new Scanner(System.in).nextInt();
       Long start= System.currentTimeMillis();
       int choice=0;
       ExecutorService l = Executors.newFixedThreadPool(1);  ;
       Future<Integer> g;
       System.out.println("Enter your choice in 15 seconds :");
       g= l.submit(k);
       while(System.currentTimeMillis()-start<15*1000 && !g.isDone()){
           // Wait for future
       }
       if(g.isDone()){
           try {
               choice=g.get();
           } catch (InterruptedException | ExecutionException e) {
               e.printStackTrace();
           }
       }
       g.cancel(true);
       return choice;
    }

推荐答案

您可以使用 标记中断(done: 在下面给出的代码中)和一个 boolean 变量(valid 在下面给出的代码)来跟踪输入是否有效.

You can do it by using labelled break (done: in the code given below) and a boolean variable (valid in the code given below) to track if the input is valid or not.

import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getChoiceWithTimeout(10));
    }

    static int getChoiceWithTimeout(int range) {
        Callable<Integer> k = () -> new Scanner(System.in).nextInt();
        Long start = System.currentTimeMillis();
        int choice = 0;
        boolean valid;
        ExecutorService l = Executors.newFixedThreadPool(1);
        Future<Integer> g;
        System.out.println("Enter your choice in 15 seconds :");
        g = l.submit(k);
        done: while (System.currentTimeMillis() - start < 15 * 1000) {
            do {
                valid = true;
                if (g.isDone()) {
                    try {
                        choice = g.get();
                        if (choice >= 0 && choice <= range) {
                            break done;
                        } else {
                            throw new IllegalArgumentException();
                        }
                    } catch (InterruptedException | ExecutionException | IllegalArgumentException e) {
                        System.out.println("Wrong choice, you have to pick an integer between 0 - " + range);
                        g = l.submit(k);
                        valid = false;
                    }
                }
            } while (!valid);
        }

        g.cancel(true);
        return choice;
    }
}

示例运行:不要输入任何内容,该方法将在 15 秒后以 0 返回,就像当前使用您的代码所做的那样

A sample run: Do not enter anything and the method will return with 0 after 15 seconds, the way it is doing currently with your code

Enter your choice in 15 seconds :
0

另一个示例运行: 一旦用户输入有效数字,该方法将返回输入值;否则,它将在 15 秒后继续请求有效输入或返回 0.

Another sample run: As soon the user enters a valid number, the method will return with the value of the input; otherwise, it will keep asking for the valid input or return 0 after 15 seconds.

Enter your choice in 15 seconds :
a
Wrong choice, you have to pick an integer between 0 - 10
12
Wrong choice, you have to pick an integer between 0 - 10
5
5

注意: 使用标记的 break 不是强制性的,您可以将其替换为传统的 breaking 方式,但这需要您再添加几行代码.

Note: Using the labelled break is not mandatory and you can replace it with the traditional way of breaking but that will require you adding a few more lines of code.

这篇关于Java中超时的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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