Home > Enterprise >  I Want to make a program that limit time when I input String by Scanner
I Want to make a program that limit time when I input String by Scanner

Time:07-02

Robot robot = new Robot();

TimerTask task = new TimerTask()
{
    public void run()
    {
        robot.keyPress(KeyEvent.VK_ENTER);
        System.out.println( "time out. exit..." );

    }
};

Timer timer = new Timer();

timer.schedule( task, 10*1000 );

Scanner sc = new Scanner(System.in);
String in = sc.nextLine();

timer.cancel();

System.out.println(in);    

I'm trying to think how can I input 'enter' without pressing enter button when the time limit arrived at 10 seconds.

so I'm going to input lots of character as many as possible util the time ends. And I want to save that String into 'in'

I just found that Robot class can press enter key, but I don't think I use it in right way.

CodePudding user response:

I think your solution is correct, you just have to define the task outside your method:

private static String str = "";

static TimerTask task = new TimerTask() {
    public void run() {
        Robot robot;
        try {
            robot = new Robot();
            robot.keyPress(KeyEvent.VK_ENTER);
        } catch (AWTException e) {
            System.err.println("Error while pressing enter - "   e);
        }
    }
};

public static void main(String[] args) throws IOException {

    Timer timer = new Timer();
    timer.schedule(task, 10 * 1000);

    System.out.println("Input a string within 10 seconds: ");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    str = in.readLine();

    timer.cancel();
    System.out.println("you have entered: "   str);

}
  • Related