NateShoffner
NateShoffner

Reputation: 16829

Using scanner to get input not printing as expected

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

I do 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 is the input for "Original price of item: $" on the next line? I was guessing it was because I went from String to double, but can't think of a different way to do it?

Upvotes: 2

Views: 2729

Answers (4)

PrinceOfMaine
PrinceOfMaine

Reputation: 201

Because you used println instead of print. The 'ln' adds a new line.

Upvotes: 1

Alex Marshall
Alex Marshall

Reputation: 10312

It's because the System.out.println() method adds a newline character to everything it prints out. If you want the prompt for input to remain on the same line, use System.out.print() (notice that's the print() method, not println()) which does not add a newline to what it sends to standard out. System.out is a static java.io.PrintStream object. You can read the Javadocs on it to help you out here : http://java.sun.com/javase/6/docs/api/java/io/PrintStream.html

Upvotes: 1

user254875486
user254875486

Reputation: 11240

If you use

System.out.println()

Java will put a newline after the output, if you use

System.out.print()

Java won't put a newline after the output.

Upvotes: 12

sdcvvc
sdcvvc

Reputation: 25654

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

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

to

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

and it will be ok.

Upvotes: 3

Related Questions