0

I'm trying to implement a program that receives user input, if no input within 1 minutes, the program ends, otherwise the timer resets and waits for user input again.

I'm only able to do a timer until now and can't find a way to implement it with user input.

import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
public class test {
    
    public static void main(String[] args){
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            int sec = 10;
            public void run() {
                if (sec > 0){
                    System.out.println(sec + "seconds");
                    sec--;
                }else {
                    System.out.println("Time's up");
                    timer.cancel();
                }
            }
        };
        timer.scheduleAtFixedRate( task, 0,1000 );
    }
}

Thanks for any help!

1 Answers1

0

Heavily inspired by this answer, I've adopted the given solution to your problem.

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Test {
  private static final int DURATION = 10;

  public static void main(String[] args) {
    Timer timer = new Timer();

    TimerTask task = new TimerTask() {
      public void run() {
        System.out.println("Failed to receive input.");
        //Maybe: System.exit(0);
      }
    };

    timer.schedule(task, DURATION * 1000);

    System.out.println("Provide input within " + DURATION + " seconds.");
    Scanner s = new Scanner(System.in);

    String input = s.nextLine();
    timer.cancel();
    System.out.println("Success! Your input was: \"" + input + "\".");
  }
}

Start the timer first, before asking the user for input to assure it is running. When java executes s.nextLine, it will wait for the user to insert something followed by a newline (Enter). While the program waits, the timer is running in the background. If an input is received in time, you can cancel the timer, else the TimerTask is executed, and you can either let the user know or exit the program (optional).

Side note: Following the Java naming convention, I've renamed the class ;)

thies
  • 19
  • 6
  • Thanks for the input! However, after the user inserted an input, the timer should restart and wait for user input again instead of doing timer.cancel(). – cheesecakefactory Oct 21 '22 at 13:26
  • You could place the code in a loop or re-schedule the task. I'm happy to update the solution if you want to maybe give a little more context if that wouldn't do it by itself. – thies Oct 21 '22 at 16:11