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
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