Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to recall a println in Java?

Say I am making a command-line interface. I want to print out a string, and then change it. For example, when you run the program, it prints out

Hello, World!

A few seconds later, though, the message gets changed to:

Hello, Computer User!

Is this possible? Cross-OS would be preferable.

like image 888
Piccolo Avatar asked Mar 07 '13 06:03

Piccolo


People also ask

How does Println work in Java?

println(): println() method in Java is also used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the start of the next line at the console. The next printing takes place from next line.

How does system out Println work?

The println() method is similar to print() method except that it moves the cursor to the next line after printing the result. It is used when you want the result in two separate lines. It is called with "out" object. If we want the result in two separate lines, then we should use the println() method.

How do you not go to the next line in Java?

You can use System. out. print() with a \r which does a carriage return without a line feed. NOTE, this was tested on W2K.


2 Answers

You could echo the \b escape sequence, which is backspace, and then write out a new message, in place of the old-one.

Do note, this might not be completely cross-platform, as it is upto the console itself and how it interprets \b, but it should work mostly.

like image 189
Anirudh Ramanathan Avatar answered Oct 01 '22 13:10

Anirudh Ramanathan


try

    String s1 = "Hello, word!";
    System.out.print(s1);
    Thread.sleep(1000);
    for(int i = 0; i < s1.length(); i++) {
        System.out.print('\b');
    }
    System.out.print("Hello, computer user");

note that it does not work from Eclipse, run it from command line

like image 27
Evgeniy Dorofeev Avatar answered Oct 01 '22 13:10

Evgeniy Dorofeev