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?
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.
To print on the same line in Python, add a second argument, end=' ', to the print() function call.
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.
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.
Use print()
instead of println()
;
System.out.println()
automatically adds a newline character. That what the ln
means.
System.out.print
instead of println
.
println adds a newline after it prints your output, print will just print your message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With