0

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.

Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
Ashkan
  • 49
  • 6

1 Answers1

0

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();
    }
}
Wild_Owl
  • 431
  • 2
  • 7
  • 1
    Creating a **new** command window and clearing it does nothing whatsoever to clear the **current** command window. – T.J. Crowder Oct 28 '18 at 11:47