0

I am trying to stop a while loop w/user input in java. I am utilizing the scanner utility. However, the scanner stops the loop from progressing. How can I make it so that the code enables user input at any time without blocking the loop?

CODE

public static void stopwatch() {
            System.out.println("When you are ready, please enter '2'.");
            Scanner reply = new Scanner(System.in);
            String two = reply.nextLine();
            if (two.matches("2")) {
                double x = 0;
                int three = reply.nextInt();
                while (three != 3) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(1);
                        x = x+.001;
                        System.out.println(x);
                        three = reply.nextInt();
                    } catch (InterruptedException e) {
                }
               }
          }
  • *scanner stops the loop from progressing.* what do you mean by stop here? *enables user input at any time without blocking the loop?* what is it that is blocking the loop? Do you not intend to accept the user input for every iteration of `while`? – Naman Sep 26 '17 at 03:38
  • If you don't block until user input is available, the loop would have no valid data for the calculations. If you're trying to delay one second between receiving user input and printing the result, try using `TimeUnit.SECONDS.sleep(1);` to delay 1 second instead of 1 millisecond. – Ted Hopp Sep 26 '17 at 15:03

0 Answers0