Console program for making time appear on the same position Console program for making time appear on the same position multithreading multithreading

Console program for making time appear on the same position


First your title is misleading, please read what Recursion means.

What you need to do is to override the curret line with the new time. This is done in a console programm by using the the carriage return charcter \r (to go back one character you can use the backspace character \b)

You could try something like this (Note that for this to work you must not print a new line charachter \n at the end of your line ):

import java.text.SimpleDateFormat;import java.util.Date;public class Time {    public static void main(String... args) throws InterruptedException {        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");        while(true) {            System.out.printf("\r%s", sdf.format(new Date()));            Thread.sleep(1000);        }    }}


Another way is to delete a number of chars from the current line ((char)8) :

public class Time {    public static void main(String... args) throws InterruptedException {        while (true) {            Date now = new Date();            System.out.print(now.toString());            Thread.sleep(1000);            for (int i = 0; i < now.toString().length(); i++) {                System.out.print((char) 8);            }        }    }}

But like A4L's answer, this won't work in every console, i.e. Eclipse.


If your problem with system.out.println() was that it printed always another line then just try using system.out.print() and after printing just give it a system.out.print(\n) or system.print.out.println()