Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading