Mehmet Karlitas
Mehmet Karlitas

Reputation: 11

Dynamic time display on Java

I am trying to make a java application that display live time of different cities. But i need to make it display on console. My problem is i can make it with using loop but it prints newline when time is changing. I am wondering if there is a way to make display live time without printing it to newline again and again. Thanks for help.

Upvotes: 1

Views: 367

Answers (2)

Andreas
Andreas

Reputation: 159135

make it display on console

For a Window Command Prompt, I know that printing a \r at the end of a line, instead of \n or \r\n, will return the cursor to the beginning of the current line, so the next printed text will print over the previous text.

I don't know if this works on Linux.

I do know that it doesn't work in the Console output panes of some IDE's, e.g. \r behaves like \n in Eclipse.

Caveats aside, in a Windows Command Prompt, the following will display a running clock on a single line:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
for (;;) { // loop forever
    LocalTime time = LocalTime.now();
    System.out.print(time.format(formatter) + "\r");
    TimeUnit.NANOSECONDS.sleep(1_000_000_000 - time.getNano());
}

Note 1: The code uses print(), not println(), since the ln will print the \r\n we don't want.

Note 2: It prints over existing text, it doesn't clear the line, so if a line prints Hello World\r then Goodbye\r, the result is the text Goodbyeorld. You need to pad with spaces to clear any existing text. This is of course not a issue with fixed-width output like HH:mm:ss.

Upvotes: 1

paulsm4
paulsm4

Reputation: 121759

Q: I'm wondering if there's a way to display ... without newline.

A: Yes.

The problem is that you appear to have a console-mode application, that uses System.out.println() (or equivalent). The solution is to use "something else".

Upvotes: 0

Related Questions