4 Replies - 583 Views - Last Post: 18 April 2010 - 06:41 PM Rate Topic: -----

#1 Guest_Mike*


Reputation:

Printing two lines at once

Posted 18 April 2010 - 01:15 PM

                        System.out.print("\nEnter the ID number: ");								
                        idNum =userInput.nextInt();
                        System.out.println("\nEnter the name: " );
                        name = userInput.nextLine();
                        System.out.print("\nEnter the price: " );
                        price = userInput.nextDouble();
                        System.out.print("\nEnter the quantity: ");
                        quantity = userInput.nextInt();
                        data.addProduct(idNum, name, price, quantity);
                        System.out.println(data);  



My code has been printing out two command lines at once, rather than one at a time. So when I run the program it displays:
Enter the ID number: (input)

Enter the name: (prints the line but skips waiting for the input from user)

Enter the price: (prints the line and waits for input)

Rather than what I want:

Enter the ID number: (input)

Enter the name: (input, displays after input from first line)

Enter the price: (input, displays after input from second line)

Is This A Good Question/Topic? 0

Replies To: Printing two lines at once

#2 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Printing two lines at once

Posted 18 April 2010 - 01:59 PM

When you input a number using idNum =userInput.nextInt(); there is still a line terminator in the input buffer. It will be read by the next call to nextLine() rather than the string the user typed.


Change

...
System.out.print("\nEnter the ID number: ");
idNum =userInput.nextInt();
System.out.println("\nEnter the name: " );
name = userInput.nextLine();
...



to

...
System.out.print("\nEnter the ID number: ");
idNum =userInput.nextInt();

userInput.nextLine(); // eat line terminator after numeric entry

System.out.println("\nEnter the name: " );
name = userInput.nextLine();
...


Was This Post Helpful? 0
  • +
  • -

#3 Guest_Mike*


Reputation:

Re: Printing two lines at once

Posted 18 April 2010 - 04:02 PM

Thanks!
Was This Post Helpful? 0

#4 Ghlavac  Icon User is offline

  • D.I.C Addict

Reputation: 84
  • View blog
  • Posts: 519
  • Joined: 14-January 09

Re: Printing two lines at once

Posted 18 April 2010 - 06:35 PM

You could also flush the userinput as well couldn't you?
Was This Post Helpful? 0
  • +
  • -

#5 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Printing two lines at once

Posted 18 April 2010 - 06:41 PM

No, java.util.Scanner does not have a flush() method.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1