0

I'm trying to create a sort of inventory storage program where users can enter, remove, and search for items and prices. However when entering values, I get an InputMismatchException. Here is the WIP code I have so far:

String item;
        double price;

        while(running == true){

            System.out.println("Enter the item");

            item = input.nextLine();

            System.out.println("Enter the price");

            price = input.nextDouble();

            inv.put(item, price);

           System.out.println(inv);

        }

What I've noticed is that on the second iteration of the loop, it skips over taking the String input. Here is the console output:

Enter the item
box
Enter the price
5.2
{box=5.2}
Enter the item
Enter the price
item
Exception in thread "main" java.util.InputMismatchException
user207421
  • 305,947
  • 44
  • 307
  • 483
NB111
  • 35
  • 4

2 Answers2

0

Add input.nextLine() as below:

String item;
        double price;

        while(running == true){

            System.out.println("Enter the item");

            item = input.nextLine();

            input.nextLine();

            System.out.println("Enter the price");

            price = input.nextDouble();

            input.nextLine();

            inv.put(item, price);

           System.out.println(inv);

        }
madhepurian
  • 271
  • 1
  • 13
0

input.nextLine() takes the Scanner to the next line of input, but input.nextDouble() does not. Therefore, you'll need to either advance the Scanner to the next line:

            price = input.nextDouble();
            input.nextLine();

Or, you can use nextLine() directly instead and parse that into a Double:

            price = Double.parseDouble(input.nextLine());

See this question for further details: Java: .nextLine() and .nextDouble() differences