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

Java中Scanner读取double值出现InputMismatch异常的问题求助

Java Scanner输入double时抛出InputMismatchException的解决方法

问题原因

你遇到的InputMismatchException,核心原因是Scanner的区域设置(Locale)和你输入的小数格式不匹配。默认情况下,Scanner会跟随系统的区域配置:

  • 比如欧洲部分国家的系统用逗号,作为小数分隔符,如果你输入的是点.就会报错;
  • 反之,如果你的系统默认用点.,输入逗号也会触发异常。

解决方法

方法1:强制Scanner使用英文区域(推荐)

在创建Scanner实例后,添加一行代码指定使用英文区域的格式,这样不管系统区域是什么,都可以用.作为小数分隔符输入:

首先在代码顶部导入Locale包:

import java.util.Locale;

然后修改Scanner初始化部分:

Scanner Inp = new Scanner(System.in);
Inp.useLocale(Locale.US); // 强制使用英文区域,小数用.分隔

方法2:跟随系统区域输入小数

比如你的系统是中文(中国),直接输入2.5即可;如果系统是法国区域,需要输入2,5(用逗号分隔小数)。但这种方法兼容性差,不推荐。

优化后的完整代码

下面是修复问题并优化格式后的代码,同时添加了Scanner资源关闭的逻辑,避免资源泄漏:

import java.util.Scanner;
import java.util.Locale;

public class BreadStore {
    public static void main(String[] args) {
        Scanner Inp = new Scanner(System.in);
        Inp.useLocale(Locale.US); // 解决小数格式匹配问题

        System.out.println("****Bread Store Inventory****");
        System.out.print("Enter the bread amount as the owner of the shop: ");
        int a = Inp.nextInt();
        if (a < 0) {
            System.out.println("ERROR: Value cannot be negative.");
            Inp.close();
            return;
        }

        System.out.print("Enter the cost of a single bread: ");
        double b = Inp.nextDouble();
        if (b < 0) {
            System.out.println("ERROR: Value cannot be negative.");
            Inp.close();
            return;
        }

        System.out.println("****Customer User Interface****");
        System.out.print("Welcome to our shop. We have " + a + " breads available. How many would you like? ");
        int c = Inp.nextInt();
        if (c <= 0) {
            System.out.println("ERROR: Value has to be a positive number.");
            Inp.close();
            return;
        } else if (a < c) {
            System.out.print("We don't have that many breads at our store, sorry.");
            Inp.close();
            return;
        }

        double d = c * b;
        a -= c;
        System.out.println("The cost is " + d + ".");
        System.out.println("Thanks for shopping with us today.");
        System.out.println("We have " + a + " breads left.");

        Inp.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:40:37