输入小数触发java.util.InputMismatchException,求问题原因及解决办法
Great question! Let's break this down clearly:
This is not an Eclipse issue — it's a code-related problem tied to your system's locale settings.
What's causing the exception?
The Scanner class uses your JVM's default locale to parse numeric input by default. In many regions (like parts of Europe), the decimal separator is a comma , instead of a dot .. When you input 5.6, the scanner expects a comma (per your system's locale) and can't recognize the dot, so it throws InputMismatchException.
How to fix it?
You have two practical solutions:
- Option 1: Use a comma instead of a dot when entering decimals (e.g., type
5,6instead of5.6). This works but isn't portable if your code might run on systems with different locales. - Option 2: Force the scanner to use a locale that recognizes dot as the decimal separator (like
Locale.US). This is the better, more universal fix.
Here's your modified code with this robust fix:
import java.util.Scanner; import java.util.Locale; // Don't forget to add this import! public class Double { public static void main(String[] args) { // Explicitly set locale to use dot as decimal separator Scanner in = new Scanner(System.in).useLocale(Locale.US); double n1, n2, sum; System.out.println("Enter the first number:"); n1 = in.nextDouble(); System.out.println("Enter the second number:"); n2 = in.nextDouble(); in.close(); sum = n1 + n2; System.out.println("the sum is " + sum); } }
Quick recap
Eclipse isn't the culprit here — the issue is that your code doesn't account for locale-specific decimal formatting. By explicitly setting the scanner's locale, you can ensure your code works consistently across different systems.
内容的提问来源于stack exchange,提问作者Netanel Nikita Sto

