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

Java如何实现用户输入时键入“end”即可终止程序运行

Java代码修改实现方案

核心修改逻辑

  • 所有用户输入统一先读取为字符串,先校验是否为end,匹配则直接终止程序运行
  • 输入最大行数阶段:读取字符串后先判断是否为end,非终止指令再转换为int数值,避免输入非数字内容抛出异常
  • 逐行输入内容阶段:每读取一次输入都优先校验是否为end,匹配即终止

修改后完整代码

import java.util.Scanner;

public class InputTerminateDemo {
    public static void main(String[] args) {
        int nom;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number max. is 10:");
        // 先读字符串判断是否是终止指令
        String firstInput = input.nextLine().trim();
        if ("end".equals(firstInput)) {
            System.exit(0);
        }
        // 转换为数字
        try {
            nom = Integer.parseInt(firstInput);
        } catch (NumberFormatException e) {
            System.out.println("请输入合法的数字!");
            input.close();
            return;
        }

        if (nom > 10){
            System.out.println("Sorry you exceed the limit of number of lines!");
            input.close();
            System.exit(0);
        }
        String[] Nput = new String[nom];
        int actualInputCount = 0;
        for(int counter = 0; counter < nom; counter ++ ) {
            System.out.println("Input anything here in line:" +(counter+1));
            String lineInput = input.nextLine().trim();
            // 判断是否是终止指令
            if ("end".equals(lineInput)) {
                System.exit(0);
            }
            Nput[counter] = lineInput;
            actualInputCount++;
        }
        input.close();
        System.out.println("Number of lines is:" + actualInputCount + "\r\nYou typed:");
        for(int counter = 0; counter < actualInputCount; counter ++ ) {
            System.out.println(Nput[counter]);
        }
    }
}

补充说明

如果需要忽略大小写匹配end(比如输入END、End也触发终止),可以把判断条件里的equals替换为equalsIgnoreCase即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:15:04