LucasMaliszewski
LucasMaliszewski

Reputation: 25

Java application that will listen for user input in a loop without pausing

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.

Upvotes: 2

Views: 680

Answers (1)

Rann Lifshitz
Rann Lifshitz

Reputation: 4090

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.

Upvotes: 1

Related Questions