I am trying to create a java console application. The application should be able to print a message to the console every x amount of milliseconds AND at the same time take in user input.
The problem is that System.out.println() apparently clears the user input field (at least on windows).
Just to make it even more confusing, if I run a Minecraft (Spigot) Server (which is written in Java) and I add a java plugin to that server, that prints “Hello, World!” (in it’s own thread of cause) every x amount of milliseconds. It doesn’t affect the user input field.
I’m running the two parts in their own threads.
I have tried to replace Scanner scanner = new Scanner(System.in);
with BufferedReader reader enter code here = new BufferedReader(new InputStreamReader(System.in));
But that didn’t seem to work
I have not tried to run this code on another OS
Main Class
public class Main {
private static final Repeater repeater = new Repeater();
private static final ReaderThread readerThread = new ReaderThread(repeater);
public static void main(String[] args) {
repeater.start();
readerThread.start();
}
}
ReaderThread Class
package org.example;
import java.util.Scanner;
public class ReaderThread extends Thread{
private final Thread applicationThread;
public ReaderThread(Thread applicationThread){
this.applicationThread = applicationThread;
}
@Override
public void run(){
while(!interrupted()){
Scanner scanner = new Scanner(System.in);
if (scanner.nextLine().equalsIgnoreCase("stop")){
System.out.println("Stops application");
applicationThread.interrupt();
interrupt();
}
}
}
}
Repeater Class
package org.example;
public class Repeater extends Thread{
@Override
public void run(){
while(!interrupted()){
try{
Thread.sleep(1000);
System.out.println("Hello, World!");
} catch(InterruptedException interruptedException){
this.interrupt();
break;
}
}
}
}
Console output
Hello, World!
Hello, World!
dsadHello, World!
dasdasHello, World!
stpoHello, World!
sotpHello, World!
sHello, World!
sotrpHello, World!
stp
Hello, World!
stpo
Hello, World!
stop
Stops application
Zedric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.