7

\n - is a new line in java, is it possible to get to the previous line from the current position? For example, I want to print "this is for test"

System.out.println("this is for");

Now how can I append "test" to the previous line since println moved carriage to the next?

zengr
  • 38,346
  • 37
  • 130
  • 192
Sergey
  • 11,548
  • 24
  • 76
  • 113

4 Answers4

9

This works:

print "\033[F\r" + "New String"

The trick is : \033[F is an ANSI code (which is supported by most terminals) to go back one line. Then, \r is to go back at the beginning of the line. You can rewrite it from there. You may need to pad it with white spaces to clear it correctly.

I don't think this is supported in the default console in Windows (cmd), but it is very likely it will work in the powershell. In Linux (and very likely MacOS), should work without any issue.

UPDATE

After 12 years since I posted this answer, it seems \033[F is no longer working in my tests. Perhaps at that time I did something else that I can't remember now. The \r works without issues for resetting the position, for example:

static void progress(int current, int total) {
    double pp = Math.round((current / total) * 10000) / 100;
    System.out.print "\rProgress: " + current + "/" + total + " (" + pp + "%) ";
}

Which you can call in a loop to display a progress.

lepe
  • 24,677
  • 9
  • 99
  • 108
  • Are you sure `"\033[F"` is a valid escape in Java? Or should it be `"\u0033[F"`? – Snackoverflow Nov 09 '21 at 12:51
  • @Snackoverflow as far I can tell is a valid escape, but after performing some tests, it seems it is not longer working for me. Not sure what I did 12 years ago that seems to work. I will update my answer. – lepe Nov 10 '21 at 03:09
  • `\033[1F` works for me on Java 17 Linux. – D-Dᴙum Jul 12 '23 at 20:47
4

I don't think you can.

You would normally use System.out.print for the first part instead and use a println() or a '\n' once you're sure your line ended.

madth3
  • 7,275
  • 12
  • 50
  • 74
1

If you really need to 'go back a character' you can do System.out.print('\b'), but unless you do, go for the other suggestions of using System.out.print first then System.out.println as it's more easy to follow.

Also, bear in mind that there's apparently a bug in Eclipse that stops this working as intended: How to get backspace \b to work in Eclipse's console?.

Community
  • 1
  • 1
SimonC
  • 6,590
  • 1
  • 23
  • 40
0

You can use System.out.print() instead to remain in the same line and append test to it .

System.out.print("this is for ");
System.out.println("test"); //System.out.print("\n");
Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57