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

如何修复java.util.InputMismatchException?Java需用逗号输入浮点数

Fixing java.util.InputMismatchException When Using Commas as Decimal Separators

Hey there! That InputMismatchException is popping up because Java's Scanner defaults to using the US locale, which expects a dot (.) as the decimal separator—but you're entering commas (,). Let's fix this quickly with a couple of straightforward solutions.

Solution 1: Explicitly Set a Locale That Uses Commas

You can tell your Scanner to use a locale that recognizes commas as decimal separators (like German, French, or Italian locales). Here's how to modify your code:

import java.util.Scanner;
import java.util.Locale; // Don't forget to import this!

public class FloatEqualityChecker {
    public static void main(String[] args) {
        // Use a locale that accepts commas for decimals
        Scanner in = new Scanner(System.in).useLocale(Locale.GERMAN);
        double epsilon = 0.001;
        
        System.out.println("Give me 2 floating numbers, and I test if they are equal with epsilon as a permissible error.");
        System.out.print("Give me the first number. ");
        double A = in.nextDouble();
        System.out.print("Give me the second number. ");
        double B = in.nextDouble();
        
        if (Math.abs(A - B) <= epsilon) {
            System.out.print("Both values are equal.");
        } else {
            System.out.print("Both values are unequal.");
        }
        
        in.close(); // Good practice to close the scanner when done
    }
}

The Locale.GERMAN setting tells Scanner to parse inputs like 2,5 as the double value 2.5. You can also use Locale.FRANCE or Locale.ITALIAN—any locale that uses commas for decimal separators will work.

Solution 2: Use the System's Default Locale (More Flexible)

If you want your program to automatically adapt to the user's system settings (so it works with dots or commas depending on where the user is), use the system's default locale instead:

Scanner in = new Scanner(System.in).useLocale(Locale.getDefault());

This way, if the user's operating system is set to a region that uses commas, the scanner will handle it automatically—no hardcoding required.

Why This Works

By default, Scanner uses Locale.US, which enforces dot-based decimal separators. By switching to a locale that uses commas, you're aligning the scanner's parsing rules with your input format, eliminating the InputMismatchException.

内容的提问来源于stack exchange,提问作者Salim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:34:20