Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep my user input on the same line after an output?

I'm trying to write code that asks for the users age and then they enter it, but I want the number to appear next to the question after you enter it.

My code looks like this:

System.out.println("Enter a number: ");
num1 = userIn.nextInt();

It works fine, but the number always appears on the line below.

Output:

Enter a number:
12

What I want:

Enter a number: 12

Any suggestions?

like image 340
user1332503 Avatar asked Apr 13 '12 21:04

user1332503


People also ask

How do you print input and output on the same line?

Modify print() method to print on the same line The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.

How do you keep an input on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call.

How do you input a single line in Java?

To do this, we could read in the user's input String by wrapping an InputStreamReader object in a BufferedReader object. Then, we use the readLine() method of the BufferedReader to read the input String – say, two integers separated by a space character. These can be parsed into two separate Strings using the String.

What are the different ways to take input from user?

In the Java program, there are 3 ways we can read input from the user in the command line environment to get user input, Java BufferedReader Class, Java Scanner Class, and Console class. Let us discuss the classes in detail. We use the Scanner class to obtain user input.


2 Answers

Use print() instead of println();

System.out.println() automatically adds a newline character. That what the ln means.

like image 140
Martijn Courteaux Avatar answered Sep 22 '22 04:09

Martijn Courteaux


System.out.print instead of println.

println adds a newline after it prints your output, print will just print your message.

like image 41
digitaljoel Avatar answered Sep 20 '22 04:09

digitaljoel