Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java terminal program output on single line

I'm creating a java application that at some point during execution needs to display several outputs on a single line by refreshing. It will need to show each output the wait for the user to confirm. I'm stuck on how to pause the output until enter is pressed. By using the following methond:

System.out.print("Test 1\r");
System.in.read();
System.out.print("Test 2\r");

however when I use this method the cursor jumps down to a new line, like so

Test 1
Test 2

Does anyone know an easy work around for this?

like image 919
Chris Maness Avatar asked Jun 25 '26 23:06

Chris Maness


1 Answers

My solution was to use ANSI since it's supported by OSX Terminal. After my scanner.next() I printed a: "1A" ANSI character to move the cursor up one line then used the "\r" to return the line to the beginning of the row. Here's how the code would look:

for(int i = 0; i<numTimesToRepeat; i++){    
    System.out.print("Print line " + i);
    System.in.read();
    System.out.print("\u001b[1A");
    System.out.print("\r");
}

Thanks for all the help everyone.

like image 166
Chris Maness Avatar answered Jun 27 '26 13:06

Chris Maness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!