2

For simplicity, I'm looking to have looping logic in the terminal that will continually process information while checking for user input without waiting for user input.

pseudo:

loop 
    If user input
        See what they've entered
    Do logic loop

Note: I've tried using a scanner with System.in and attempting to see if the next line was empty. Unfortunately, that implementation still causes the application to pause.

3
  • 2
    Start a second Thread with the Scanner waiting for input on that Thread. Commented Apr 7, 2018 at 15:45
  • 1
    Like @camickr mentioned - Is your motivation for this solution to have the application continue running, so the user will not experience a pause while waiting for input? if that is the case - then an input handling thread like the one suggested above would work like a charm. Commented Apr 7, 2018 at 15:48
  • Perfect! Thank you for the information. Commented Apr 7, 2018 at 19:40

1 Answer 1

1

Based on a comment from camickr and the following post, you can use the following algorithm:

     public class ScannerRunner implements Runnable {
         private Scanner sc;
         private ScannerRunner() {/* no instantiation without parameters*/}
         public ScannerRunner(Scanner sc) {
            this.sc = sc;
         }
         @Override
         public void run() {     
            System.out.println("Enter The Correct Number ! ");
            int question = sc.nextInt(); 

            while (question!=1){
               System.out.println("please try again ! ");
               question = sc.nextInt(); 
            }
            System.out.println("Success");
        }
     }

Then, create a scanner in you main thread, then spawn a thread using the above Runner (constructed with the scanner you provided), and have your main thread listen to inputs on the scanner. The Scanner API should help you out.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.