You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入小数触发java.util.InputMismatchException,求问题原因及解决办法

Why does my Java code throw InputMismatchException when entering a decimal like 5.6?

Great question! Let's break this down clearly:

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,6 instead of 5.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 14:42:43