I am writing a program which gets numbers from the user (using a Scanner
) frequently. But before getting a new number, I want to clean the console from the previous result.
I tried System.out.print("\033[H\033[2J");
but it did not work.
I am writing a program which gets numbers from the user (using a Scanner
) frequently. But before getting a new number, I want to clean the console from the previous result.
I tried System.out.print("\033[H\033[2J");
but it did not work.
tldr;
Linux Solution:
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
Windows Solution:
Runtime.getRuntime().exec("cls");
NOTE: On Windows OS, you can have a problem with redirecting output to newly created process. To solve this, please use ProcessBuilder
instead.
public class ClearScreen {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}