Reputation: 115
So I am actually trying to make a stopwatch application that acts like an exact stopwatch so it needs to take input so what I want to do is whenever the user enters something the loop will break.....
This is my code..........
public class Stop {
public static void stopwatch() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter anything when you want to stop");
for(double i = 0; true; i+=0.5) {
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
So, I want to take an input but it should be optional whether the user enters or not if he enters the loop will break else it will continue...
My output should be like
Enter anything when you want to stop
0.0
0.5
1.0
1.5
stop
You stopped
How do I do that?
Upvotes: 1
Views: 56
Reputation: 288
You can do it this way:
public static void stopwatch() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter anything when you want to stop");
for (double i = 0; true; i += 0.5) {
try {
if (!br.ready()) {
System.out.println(i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You have to type something and press Enter if you're running it in IDE console. Do not use Scanner as it blocks and waits for the input.
Upvotes: 1