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

Java Scanner输入验证异常求助:重复输入字符串触发InputMismatchException

解决Scanner输入正整数时的InputMismatchException问题

需求

实现仅允许用户输入正整数的功能,若输入字符串、零或负整数,需提示用户重新输入直至输入正确。

用户原有代码

int id;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Your Id: ");

do {
    while (!scanner.hasNextInt()) {

        System.out.println("You have entered invalid ID, expecting Integer");
        System.out.println("Enter Id again");
        scanner.nextLine();
    }

    id = scanner.nextInt();

    while (id <= 0) {

        System.out.println("Pl enter positive ID only");
        id = scanner.nextInt();

    }

} while ((!scanner.hasNextInt()) || (id <= 0));

问题描述

当输入字符串后按提示修正,再输入负数再次修正,随后再次输入字符串时,调用scanner.nextInt()触发InputMismatchException。

问题原因

  1. 输入负数后,若用户再次输入字符串,内层while(id <= 0)循环会直接调用nextInt(),此时输入的不是整数,直接抛出异常。
  2. 调用nextInt()后,缓冲区残留的换行符未被处理,可能导致后续hasNextInt()的判断出现偏差。
  3. 外层do-while的条件逻辑冗余,无法覆盖所有异常输入场景。

修正后的代码

import java.util.Scanner;

public class PositiveIntegerInput {
    public static void main(String[] args) {
        int id;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Your Id: ");

        do {
            // 先校验输入是否为整数,处理非整数输入
            while (!scanner.hasNextInt()) {
                System.out.println("You have entered invalid ID, expecting Integer");
                System.out.println("Enter Id again");
                scanner.nextLine(); // 清空缓冲区的无效输入
            }
            
            // 读取整数后,清空残留的换行符
            id = scanner.nextInt();
            scanner.nextLine();

            // 校验是否为正整数,同时处理非整数输入的情况
            while (id <= 0) {
                System.out.println("Pl enter positive ID only");
                
                // 再次校验输入是否为整数,避免直接输入字符串抛异常
                while (!scanner.hasNextInt()) {
                    System.out.println("You have entered invalid ID, expecting Integer");
                    System.out.println("Enter Id again");
                    scanner.nextLine();
                }
                
                id = scanner.nextInt();
                scanner.nextLine(); // 清空换行符
            }
        } while (id <= 0); // 只要id是正整数就退出循环
    }
}

修正说明

  • 每次调用nextInt()后添加scanner.nextLine(),彻底清空缓冲区中的换行符,避免残留字符干扰后续输入判断。
  • 在处理非正整数的循环内,新增整数校验逻辑,确保用户输入字符串时不会直接调用nextInt()触发异常。
  • 简化外层do-while的条件,逻辑更清晰,只要输入的id是正整数就终止循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:18:26