Clearing Terminal Screen in Java
I tried to make a Simple Clock in Java
My Expected Output was 00:00:00
// Showing Time
My Actual Output Was
00:00:00
00:00:01
00:00:02
.......
I tried many things and was unable to clear previous output after being printed
Thanks for Reading, Hope somebody will give a valuable feedback
Code:
package com.company.Time;
import java.util.Scanner;
import java.util.Date;
public class Main {
public static void main(String[] args) {
System.out.println("Enter Time");
System.out.println("Enter Hour :");
Scanner sc = new Scanner(System.in);
int h = sc.nextInt();
System.out.println("Enter Minutes :");
Scanner sc2 = new Scanner(System.in);
int m = sc2.nextInt();
System.out.println("Enter Seconds :");
Scanner sc3 = new Scanner(System.in);
int s = sc3.nextInt();
int i = 0;
try {
while (i < 1)
{
for (; h < 24; h++)
{
for (; m < 60; m++)
{
for (; s < 60; s++)
{
System.out.println(h + ":" + m + ":" + s);
System.out.print("\u000C");
Thread.sleep(1000);
}
s = 0;
}
m = 0;
}
}
}
catch(Exception exception)
{
System.out.println("Ushh");
}
}
}
Solution 1:
Replace this:
System.out.println(h + ":" + m + ":" + s);
System.out.print("\u000C");
With this:
System.out.print(h + ":" + m + ":" + s + "\r");
The carriage return symbol (\r
) returns the cursor at the start of the line. You must use print()
and not println()
for it to work. If the program jumps to a new line, the previous line is left as is.