• Coding
  • [Java] Wait a few seconds for user input

Hello,

How can I tell JAVA to wait lets say 5 seconds for a user to input a string, but then continue the while loop if the user decides to enter nothing ?

for instance
    input = scan.nextLine(); //Wait three seconds or else just skip this statement
By the way, am I thinking at this issue the wrong way ?
Maybe you need to use an interval timer... I don't know much Java, just JavaScript, and JS is an "asynchronous" language, there is no sleep() function as in PHP - but there is setInterval() and setTimeout(). I have a feeling Java is similar.
The code should look something like this:
input = scan.nextLine();
long referenceTime = new Date().getTime(); //in milliseconds i guess
long currentTime = new Date().getTime();
while ((currentTime - referenceTime) < 5000) {
   //wait for user input
   currentTime = new Date().getTime();
}
rami wroteThe code should look something like this:
input = scan.nextLine();
long referenceTime = new Date().getTime(); //in milliseconds i guess
long currentTime = new Date().getTime();
while ((currentTime - referenceTime) < 5000) {
   //wait for user input
   currentTime = new Date().getTime();
}
Won't that totally screw the CPU? Unless there is some kind of intelligent optimization/compilation...
How about you create a new thread and make it sleep for 5 seconds while waiting for the user input
Hm... Here's the dilemma: If you use the sleep function the user won't be able to input anything and if you use the loop you have more flexibility but less efficiency. I guess you can add
Thread.sleep(50);
in the loop to add some efficiency.
Source http://stackoverflow.com/questions/580419/how-can-i-stop-a-java-while-loop-from-eating-50-of-my-cpu
I'm not sure how Java manages threads (or whether it just leaves it up to the OS), but creating a new thread is definitely not the way to go. User input should always be captured on the main thread, that is the UI thread.

The loop suggested by rami should do the trick, but yes that's too much work for the CPU to achieve something as simple as that.
I agree with Paladin. There is no way for you to do this, unless you go for a context switch (threading or processes). I don't know Java well enough to give you a code unfortunately.

On the other hand, you asked if this is the good way to go, and to me, it seems a bit too complicated.

You want to put a timeout on a user's input, and that's great. Can you give us more background about the app, so we can discuss other approaches?
There are dozens of ways you can do this. I can think of three quick ways each with its own strength.

1) Quick and dirty as a hack, you spawn a new thread to read input and interrupt it from the main thread after a delay. Definitely worst implementation.
2) Detailed and clean, classic case of consumer/producer, make use of wait(), notify()
3) Using the latest java concurrency api, haven't used those before.

Either way, I think you're approaching it wrong, as rahmu said, what's the background of the application?
@xterm: Got any good doc about the Java concurrency you mention?
xterm wrote1) Quick and dirty as a hack, you spawn a new thread to read input and interrupt it from the main thread after a delay. Definitely worst implementation.
But in this case the user's input will not be visible on the UI until you marshal it to the UI thread, right?
rahmu wrote@xterm: Got any good doc about the Java concurrency you mention?
I don't know about good, but here are the official docs. Sadly I haven't placed much effort, but i presume what YOU would be interested in is Futures.

P.S. to All: Make no mistake about the entire concurrency paradigm in Java, the all powerful and mighty EE makes use of it extensively.
Kassem wroteBut in this case the user's input will not be visible on the UI until you marshal it to the UI thread, right?
You would think, except Java doesn't complain about accessing objects spawned by different threads than the owner. Unless they changed it, which i don't think they did.

Quick Update: Swing no longer allows manipulating its objects on anything other than its own thread.
Hello ! Thanks for all the replies :) Im fairly still new with Java thus I have no experience with Threads but I'm sure I would get the hang of it easily if necessary.

Second the program is fairly simple, it accesses a certain website and keeps on refreshing while tracking if any changes are made to the site. Once a change is made, a boolean value is set to false which stops the while loop.
What Im basically trying to achieve is exactly how Rahmu put it, I want to put a timeout on a user's input value, so for instance, I'd like to to stop running the while loop if the boolean value is set to false OR the user enters lets say "Stop" while the program is running.

Edit: I dont want to terminate the program by entering Stop, I just want it to break out of the while loop that's refreshing the page.
Leonedes wroteI'd like to to stop running the while loop if the boolean value is set to false OR the user enters lets say "Stop" while the program is running.
while ( boolean == True)     
{
    input = scan.nextLine(); 

    if (somethingHappens() || input == "Stop")        // Check correct Java syntax for comparing strings
    {
        boolean = False;
    }
}
I don't know how correct a Java syntax this is. Don't hesitate to ask if you're unsure about anything.
Thanks again, but the fact is that if the user doesnt input anything, the java program will stop and wait for an input, which goes back to the problem of how to tell java to continue the program after a certain amount of time if the user doesnt input anything.
let me give you some guidelines for the solution, I hope they help you with what you are doing:
1 in the main class, you create a boolean variable, name it "userStop, and set it to false;
2 you create a while loop to check if the website has changed, within this loop, you put an if-condition to check if the userStop OR the website changed is true, you break the loop.
3 you create another thread (from within the main) that asks for user input, if it gets it within the specified time (5 seconds) then you set userStop accordingly. else, you stop the thread, your userStop variable will remain false and your loop will just continue until the website is changed.
4 you can make the loop sleep for sometime for optimisation.

I hope this solution helps you, it's just a midnight thought that I wanted to share :)

could you please be more specific with what you need this function for? I am suspecting you want to use it for some DOS attacks :P
@ isomorphism :

Its a program that tracks scoreboards of football games and sends me a message as soon as the score changes ... I cant get the program to stop refreshing the page whenever I want to, I can only terminate it totally.
I cant get the program to stop refreshing the page whenever I want to, I can only terminate it totally.
can't you have the page reading loop in a new thread, and pause/resume it from the main thread?
As I said im fairly new to Java , ill catch up on threads and try your method thanks :)