how to clear the screen by pressing a key in java

how to clear the screen by pressing a key in java

To clear the screen by pressing a key in Java, you can use the following code:

refer to‮‬:lautturi.com
import java.io.IOException;
import java.util.Scanner;

public class ClearScreen {

  public static void main(String[] args) throws IOException, InterruptedException {
    Scanner scanner = new Scanner(System.in);
    while (true) {
      System.out.print("Press any key to clear the screen: ");
      scanner.nextLine();

      // clear the console
      new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
  }
}

This code uses a Scanner object to read input from the console, and then enters an infinite loop that waits for the user to press a key. When a key is pressed, the code uses the ProcessBuilder class to execute the "cmd" command with the "/c" option and the "cls" command, which clears the console. The inheritIO method is used to redirect the output of the command to the current terminal, and the waitFor method is used to wait for the command to complete before continuing with the program.

Note that this code will only work on Windows systems. On other systems, you can use a similar approach by calling the appropriate command for clearing the console. For example, on a Unix-based system, you can use the "clear" command.

Created Time:2017-11-01 12:05:14  Author:lautturi