2

I want to be able to enter a number using nextInt() and then print text on the same line as the number I entered. For example...

Scanner scan = new Scanner(System.in);
System.out.print("Enter your number: ");
int x = scan.nextInt(); //After you press 'enter' it goes to the next line and keeps printing text
System.out.print("I want this on the same line as my number!");

And the output would look something like this:

Enter your number: 4356
I want this on the same line as my number!

Is there a way I can get the text to print right after the number? So it would look something like this?...

Enter your number: 4356 I want this on the same line as my number!
  • 2
    While I can't give you an answer, I suspect this is likely to be a console issue rather than a Java one *per se*. When you hit the `Enter` key after inputting the number, it's the **console** that decides to move the cursor to the start of the new line - it's not Java that decides to do it. So any solution will involve Java somehow changing the natural behaviour of the console and may well be environment-specific. – Andrzej Doyle Aug 11 '11 at 08:31

2 Answers2

2

Have you tried

System.out.print("\rI want this on the same line as my number!");

But note that because the user has to press the Enter key, there's no way (AFAIK) to go a line backwards and erase till the beginning of it.

adarshr
  • 61,315
  • 23
  • 138
  • 167
  • This will not print the number on the previous line, but will print the result and then insert a line b/w the Previous line and the result line. – Logan Aug 11 '11 at 08:52
  • Tried. Still printing on next line and not on same line. – Logan Aug 11 '11 at 09:06
  • @Logan - Strange! It works perfectly for me! Just put these three lines in a main and run it from command prompt: System.out.print("Hello World:"); Thread.sleep(5000); System.out.print("\rHey, this is me speaking..."); – adarshr Aug 11 '11 at 09:21
  • @Logan - the problem is when we read input from the user. The user has to press the "Enter" key for that. We can't go a line back up and remove the enter. – adarshr Aug 11 '11 at 09:23
2

On Windows, I'm pretty sure the answer is "no", because there doesn't seem to be any reverse line feed (see this question: Reverse line feed in Windows / Java).

Community
  • 1
  • 1
Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180