简体   繁体   中英

How to Update the console output in java?

I have to update my console.

Here is an example code:

public class Tester {
    public static void main(String[] args) {
        System.out.print("abcd\n");
        System.out.print("efgh");
        System.out.print("\r\r\rijkl");
}
}

My output:

abcd
ijkl

Expected output :

ijkl
efgh

I'm also tried this:

        System.out.print("abcd\n");
        System.out.print("efgh\n");
        System.out.print("\033[0;0H");//\033[0;0H is an escape sequence to positioning the console cursor(Referred From Internet).
        System.out.print("ijkl");

For the above Code the output is :

abcd
efgh
←[0;0Hijkl

While I try online compiler the above code working fine. see here

But it is not working in windows and linux OS

Please Tell me What change i have to make to get my expected output.

Thank you all.

You need to learn difference between the char literal \\n and \\r . It varies from system to system. While both of them are used in similar sense, yet they work differently. \\r works as a Carriage Return. It simply push the cursor back to the start of the line. In your case it is exactly mimicking the same scenario.

When compiler compiles this piece of code System.out.print("abcd\\n"); // prints abcd on console. System.out.print("efgh"); // prints efgh on console. System.out.print("\\r\\r\\rijkl") // takes the cursor at the start of the line, overrides previous characters and print ijkl on console respectively. So, if you are using \\r then try using `System.out.println' as it will print the literals in the new line, Though it will still move the cursor to the start of the line, first. But it will implicitly print characters on the second line.

For more information, refer to this question

To see the difference between \\r and \\n you must run your code from a command prompt. Eclipse's Console (and similar for other IDEs) does not simulate the behavior of a full terminal and will move to the next line for both \\r and \\n. On the command line, however, \\r will only move the cursor back to the beginning of the current line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM