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?
source to share
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
source to share