Using the scanner to take input does not print as expected

This is for a friend of mine having problems with Java for school.

I know some programming, but not Java.

Scanner kbReader = new Scanner(System.in);
System.out.print("Name of item: ");
String name = kbReader.next();
System.out.println("Original price of item: $");
double price = kbReader.nextDouble();

      

Outputs:

Name of item: Coat
Original price of item: $

10

      

Why enter "Starting price of item: $" on the next line? I assumed it was because I moved from String

to double

, but can't think of another way to do it?

+2


source to share


4 answers


If you are using

System.out.println()

      

Java will print a newline after the output if you use



System.out.print()

      

Java will not put a newline after the output.

+12


source


You haven't posted all the code. But, change

System.out.println("Original price of item: $");

      

to



System.out.print("Original price of item: $");

      

and all will be well.

+3


source


This is because the System.out.println () method adds a newline character to whatever it prints. If you want the prompt to stay on the same line then use System.out.print () (note that the print () method, not println ()), which does not add a newline to what it sends in a standard way. System.out is a static java.io.PrintStream object. You can read the Javadocs on it to help you here: http://java.sun.com/javase/6/docs/api/java/io/PrintStream.html

+1


source


Because you used println instead of printing. "Ln" adds a new line.

+1


source







All Articles