You need to enable JavaScript to run this app. Java程序如何校验数字输入 拦截字母/单词类非法输入并给出提示
优惠活动
大模型
产品
解决方案
定价
更多

Java程序如何校验数字输入 拦截字母/单词类非法输入并给出提示

问题原因

原代码直接调用Scanner.nextInt()读取用户输入,碰到字母、单词等非数字内容时会直接抛出InputMismatchException运行时崩溃,既无法输出自定义的INVALID INPUT提示,也会因为非法内容残留在Scanner的输入缓存中,导致后续读取逻辑卡死。

实现方案

不需要手动写字符串拆分、字符遍历这类复杂的if判断做校验,直接利用Scanner自带的输入预判能力就能稳定实现校验逻辑:

  • 每次需要读取整数前,先调用input.hasNextInt()检查当前待读内容是否为合法整数
  • 输入为合法整数时,直接读取存入对应位置
  • 输入为非数字内容时,先调用input.next()清空缓存中的非法输入,打印INVALID INPUT提示,循环等待用户重新输入,直到拿到合法值
  • 这套逻辑可以直接复用到数组元素输入、后续索引值输入所有需要读取整数的环节,顺带可以补充索引范围校验,避免数组越界访问崩溃
改造后可直接运行的代码
import java.util.Scanner;
public class ArrayAccessDemo {
    public static void main(String[] args) {
        int [] Array = new int[10];
        int index;
        Scanner input = new Scanner(System.in);

        System.out.println("Enter 10 elements:");
        for (int i = 0; i < Array.length; i++) {
            // 循环校验每一次数组元素的输入
            while (true) {
                if (input.hasNextInt()) {
                    Array[i] = input.nextInt();
                    break;
                } else {
                    System.out.println("INVALID INPUT");
                    // 丢弃非法输入,清空Scanner缓存避免死循环
                    input.next();
                }
            }
        }

        System.out.print("Enter an index you want to retrieve: ");
        // 循环校验索引值的输入
        while (true) {
            if (input.hasNextInt()) {
                index = input.nextInt();
                // 校验索引是否在数组合法访问范围内
                if (index >= 0 && index < Array.length) {
                    break;
                }
                System.out.println("INDEX OUT OF BOUNDS");
                input.next();
            } else {
                System.out.println("INVALID INPUT");
                input.next();
            }
        }

        System.out.print("Element at index " + index + " is " + Array[index]);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.25 07:15:02