Java练习遇InputMismatchException:输入带小数点价格报错求助
Troubleshooting Your Java InputMismatchException & Code Issues
Hey there, let's break down the problems you're facing step by step:
1. Root Cause of java.util.InputMismatchException
The error happens because Scanner.nextDouble() relies on your system's default locale settings to parse decimal numbers. For example:
- If your system uses a locale where commas (
,) are the decimal separator (like many European locales), entering a number with a dot (.) will trigger this exception. - Conversely, if your locale uses dots but you input a comma, you'll get the same error.
Fix for the Exception
You can force the Scanner to use a locale that expects dots as decimal separators (like US English) by adding one line after initializing the scanner:
in.useLocale(java.util.Locale.US);
This ensures that inputs like 12.99 are parsed correctly regardless of your system's default locale.
2. Other Bugs in Your Code
There are two small but important issues in your current code:
- Missing element in total calculation: You're adding
prices[0] + prices[1] + prices[2] + prices[4]but skippingprices[3]—this means your total will be incorrect (you're only summing 4 items instead of 5). - Incorrect
printfsyntax: You're concatenating the format string withtotalusing a+sign, which is not howprintfworks. Also, you have a typo (tot1alinstead oftotal). The correct syntax is to passtotalas a separate argument toprintf.
Corrected Full Code
Here's the fixed version of your code with all issues addressed:
package grocerystore; import java.util.Scanner; import java.util.Locale; // Import required for locale setting /** * * @author aslan */ public class GroceryStore { /** * @param args the command line arguments */ public static void main(String[] args) { double [] prices = new double [5]; Scanner in = new Scanner(System.in); in.useLocale(Locale.US); // Fix decimal parsing issue System.out.println("Enter 5 prices: "); prices[0] = in.nextDouble(); prices[1] = in.nextDouble(); prices[2] = in.nextDouble(); prices[3] = in.nextDouble(); prices[4] = in.nextDouble(); // Include all 5 prices in total double total = prices[0] + prices[1] + prices[2] + prices[3] + prices[4]; // Correct printf syntax and fix typo System.out.printf("The total of all 5 items is: $%5.2f", total); } }
Testing Tips
- If you prefer to use your system's default decimal separator instead of forcing US locale, just remove the
in.useLocale(Locale.US)line and make sure your input matches the separator your system expects (e.g., use12,99if your locale uses commas).
内容的提问来源于stack exchange,提问作者Aslan Ali
相关产品推荐
相关产品推荐

