0
Timer timer=new Timer();
TimerTask task=new TimerTask(){
    @Override
    public void run() {
        if(isTimeCompleted){
            System.out.println("Time over");
            System.exit(0);
        }   
    }
};
timer.schedule(task, 5000);

System.out.println("Type your word within 5 seconds..");

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

I have used above code to take input from user within 5 seconds but I have to hit enter after giving input wiithin 5 seconds. I don't know this should work like it would not require to press Enter if i have given input within 5 seconds .Any help will be appreciated. Thanks in advance.

azro
  • 53,056
  • 7
  • 34
  • 70
  • Try this. https://stackoverflow.com/a/1066647/13528037 – Natsu May 27 '20 at 11:09
  • Note: This question has nothing to do with threads or timers. This is a question about how to read input from a console keystroke-by-keystroke instead of reading it line-by-line. Last time I checked, support for console I/O within a _pure_ Java program was rudimentary—there's not much else that a pure Java program can do with the console _except_ line-by-line I/O. The answer to which @Natsu linked may solve your problem, but it may also take you somewhere beyond the realm of pure Java. – Solomon Slow May 27 '20 at 13:21
  • P.S.: If you don't expect the user to press [Enter], then how will your program recognize when they have finished typing a word? E.g., after the user has typed 'f' and 'i' and 'g', how will you know whether they meant to type "fig" or "figure"? – Solomon Slow May 27 '20 at 13:25

0 Answers0