0

I’m trying to read 6 lines of user input, but I can’t get them to print correctly.

I first did this:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String name, name2;
        double price, price2;
        int item, item2;

        System.out.print("Name: ");
        name = input.next();
        System.out.print("Price: ");
        price = input.nextDouble();
        System.out.print("Item Number: ");
        item = input.nextInt();
        System.out.println("");

        System.out.print("Name 2: ");
        name = input.next();
        System.out.print("Price 2: ");
        price = input.nextDouble();
        System.out.print("Item Number 2: ");
        item = input.nextInt();
        System.out.println("");
    }
}

And after I test it won't let me input past "Price:" (I'm on BlueJ btw).

Name: Jack B

Price: 

I tried with input.nextLine(); instead of input.next(), but ended up with this

Name: Jack B

Price: 30

Item Number: 10

Name 2: Price 2:

It works if the String doesn’t have spaces, but if it has one, this will happen. How do I get it to print the 6 lines normally?

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
TPJB
  • 13
  • 3

2 Answers2

0

You need to "flush the buffer".

Whenever you read an int, you are actually reading the string value of the integer, not including the newline character, and converting it to an int.

When you call nextInt(), and enter 42, the buffer looks like this.

"42\n"

After you read the int, the buffer still contains the newline character.

"\n"

When you call nextLine(), it reads the newline character from the buffer, and returns an empty String.

The solution. Call nextLine() after reading each int, double, etc., to read and discard the trailing newline character.

int i = input.nextInt(); // read integer value
input.nextLine(); // read and throw away newline character
the_storyteller
  • 1,913
  • 20
  • 30
0

Two suggestions:

  1. Use nextLine instead of next to read the whole line including spaces.
  2. Use an extra nextLine after you do the first nextInt. This is needed to consume an extra line break that you enter but is not consumed by nextInt.

See the following workig snippet:

    Scanner input = new Scanner (System.in);
    String name, name2;
    double price, price2;
    int item, item2;

    System.out.print("Name: ");
    name = input.nextLine();
    System.out.print("Price: ");
    price = input.nextDouble();
    System.out.print("Item Number: ");
    item = input.nextInt();
    System.out.println("");

    input.nextLine();
    System.out.print("Name 2: ");
    name = input.nextLine();
    System.out.print("Price 2: ");
    price = input.nextDouble();
    System.out.print("Item Number 2: ");
    item = input.nextInt();
    System.out.println("");
VHS
  • 8,698
  • 3
  • 14
  • 38