Hugo Schongin Hugo Schongin - 1 year ago 97
Java Question

How do i replace text that's been printed out on screen already in Java?

I'm new to Java and as an attempt to learn more I tried making a clock. It works perfectly except the fact that it prints on a new line every time a second changes. How do I make it so that I can replace the text that's already been printed out with the new time?

public class test {
public static void main(String[] args) {
public static void clock(){
int sec = 0;
int min = 0;
int h = 0;
if(sec == 60)
sec = 0;
if(min == 60)
min = 0;
if(h == 24){
h = 0;
{try {
} catch (InterruptedException e) {
if(h < 10){
} else{
if(min < 10){
} else{
if(sec < 10){
} else{

Here's my code. And here's an example of what I'm trying to do:
I want to turn this: 00:00:00
Into this: 00:00:01 (the code does this but it prints on a new line and doesn't delete the old time)
The thing is that I want to get rid of the first one(00:00:00) and on the same line print the second one(00:00:01).

Is this possible in Java?

Answer Source

That has nothing to do with java actually. Rather you want the console you are displaying in to overwrite the text.

This can be done (in any language) by sending a carriage return (\r in Java) instead of a linefeed (\n in Java). So you never use println(), only print() if you want to do that. If you add a print("\r") before the very first print it should do what you want.

BTW it would be far more elegant and simple if you built the entire time in a string and then output it all at once :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download