1

How to clear the screen in Java?

I have created one menu driven simple demo program using while loop and switch case. After one loop completes, I want to clear a screen but that's not working. I will be glad for a possible solution to this.

I am using JDK 7 and running the program in command prompt.

import java.util.*;
class DemoPrg
{
    public static void main(String argv[])
    {
        int ch;
        Scanner sc=new Scanner(System.in);
        while(true)
        {
            // i want to clear the scrren hear
            System.out.println("1. Insert New Record");
            System.out.println("2. Display Record");
            System.out.println("3. Delete Record");
            System.out.println("4. Edit Record");
            System.out.println("0. Exit");
            System.out.print("Enter Your Choice:");
            ch=sc.nextInt();
            switch(ch)
            {
                case 1:
                    System.out.println("insert");
                    break;
                case 2:
                    System.out.println("display");
                    break;
                case 3:
                    System.out.println("delete");
                    break;
                case 4:
                    System.out.println("edit");
                    break;
                case 0:
                    System.exit(0);
                default:
                    System.out.println("invalid");
            }
        }   
    }
}
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Hiren Raiyani
  • 754
  • 2
  • 12
  • 28

1 Answers1

0

Sorry, but this is impossible to do in a generic way.

The reason is, your program has no clue what the screen is. System.out can refer to anything, NUL-device, some kind of console or even a file. The console may allow clearing, but how the console is to be cleared depends entirely on the type of the console (The usual console in an IDE can not be cleared, that would contradict its purpose of logging program output, while the console of a DOS-prompt/shell usually can be cleared).

Your best bet would be to assume the console does support ANSI codes and send the ANSI control code for clear screen as suggested in the comments by MohdAdnan:

System.out.print("\u001b[2J");
System.out.flush();
Durandal
  • 19,919
  • 4
  • 36
  • 70