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

为什么简单Java代码会出现java.util.InputMismatchException异常?

错误排查

  • 缺少java.util.Scanner类的导入声明,JDK不会默认导入该工具类,未导入会直接触发编译报错
  • 代码存在拼写错误:Sytstem.in应为System.in,拼写错误会导致编译阶段无法识别对应变量
  • 若编译通过后运行仍抛出异常,是因为你实际输入的内容不符合整数格式:nextInt()仅能解析合法整数输入,输入字母、小数、特殊符号都会触发InputMismatchException

修正后代码

import java.util.Scanner;

class Main {
    public static void main(String args[]) {
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
       int sum = 2 + n;
       System.out.println(sum);
       sc.close();
    }   
}

运行说明

  • 程序启动后直接输入纯整数,不要添加多余的空格、字符或格式
  • 输入完成后按回车即可输出计算结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:45:04