0

I want to show some timer in java eclipse output . I have successfully implement the function but the problem is this that after every second timer is printing in new line but i want to replace the text of each second in same line. For example my i input 12 secs so the output shows like

11
10
9
8
7
6
5
4
3
2
1
0

I want to show the second change in same line. This is my code

public class Stopwatch {
static int interval;
static Timer timer;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Input seconds => : ");
    String secs = sc.nextLine();
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = Integer.parseInt(secs);
    System.out.println(secs);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            System.out.println(setInterval());

        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}
}
  • 1
    use print instead of println .print("") method prints the text on the console and the cursor remains at the end of the text at the console. – Atif AbbAsi Nov 04 '19 at 12:45

2 Answers2

1

You can try printing first the '\r' character as per this. Also do not use println() but print() method :

...
public void run() {
     System.out.print('\r');
     System.out.print(setInterval()); 
}
...
nullPointer
  • 4,419
  • 1
  • 15
  • 27
0

Console is a LOG-Tool it can't be cleared using code .. you can right click console and choose clear manually .

Mohammad
  • 739
  • 7
  • 22