Programm a loop that goes on until you enter something into console

Viewed 86

I'm trying to build a loop, that executes a specific method when I enter text into the console. I want to use the java.util.Scanner but when I try to use .hasNext() for checking inside if() and then .next() to get the input it waits until I enter something instead of looping on.

while(true) {
    main_loop();
}

private void main_loop() {
    do_other_things(); 
    if(sc.hasNext()){
        System.out.println("user entered " + sc.next());
    } else {
        System.out.println("user entered nothing");
    }
}

How can I make it output "user entered nothing" until I enter something, so that it outputs "user entered [...]" and then goes on with "user entered nothing"?

2 Answers

Make use of another thread:

public static void main(String[] args) {
    new Thread(() -> {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            if (scanner.hasNext()) {
                //... user has input
            }
            else {
                //... user does not have input
            }
    }).start();
    doSomethingElse();
}

You need to have a seperate thread run to wait for the input then (if you want this to trigger if the user inputs a second string) once it has processed the input, schedule the runnable again.

    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    Scanner scanner = new Scanner(System.in);
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (scanner.hasNext()) {
                String st = scanner.next();
                //do something now the user has inputted
                System.out.printf("The user entered a string! (%s)", st);

                //run the runnable to wait again
                executorService.schedule(this, 0, TimeUnit.SECONDS);
            }
        }
    };
    executorService.schedule(runnable, 0, TimeUnit.SECONDS);
}
Related