Michel Rothboeck :
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"?
Frontear :
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();
}