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

Java程序中如何为整数输入功能添加退出选项?

解决猜数字游戏中途退出的实现方案

当前代码的核心问题是使用sc.nextInt()强制读取整数类型输入,无法识别字符串指令"quit"。要实现中途退出,需要先读取用户输入的完整字符串,再进行判断和类型转换,具体实现如下:

核心修改思路

  • 先读取用户输入的完整字符串,优先判断是否为退出指令"quit"(支持大小写不敏感)
  • 若不是退出指令,尝试将字符串转换为整数,处理转换失败的异常(如输入非数字内容)
  • 验证数字范围后,再执行原有的猜数字逻辑

修改后的完整代码

import java.util.Scanner;
import java.util.Random;

public class NumberGuesser {

    public static void playGuess() {
        Random rand = new Random();
        Scanner sc = new Scanner(System.in);
        int answer = rand.nextInt(50 - -50 + 1) + -50;
        int totalGuesses = 1;

        while (true) {
            System.out.println("请输入-50到50之间的数字,或输入quit退出游戏。");
            String input = sc.nextLine().trim();

            // 判断是否触发退出
            if (input.equalsIgnoreCase("quit")) {
                System.out.println("游戏已退出。");
                break;
            }

            int guess;
            try {
                // 尝试转换为整数
                guess = Integer.parseInt(input);
            } catch (NumberFormatException e) {
                System.out.println("输入无效,请输入数字或quit。");
                continue;
            }

            // 验证数字范围
            if (guess > 50 || guess < -50) {
                System.out.println("输入错误,请输入-50到50之间的数字。");
            } else if (guess == answer) {
                System.out.println("答对了!你一共猜了" + totalGuesses + "次。");
                break;
            } else if (guess < answer) {
                System.out.println("数字更大哦。");
                totalGuesses++;
            } else {
                System.out.println("数字更小哦。");
                totalGuesses++;
            }
        }
    }

    public static void main(String[] args) {
        boolean playAgain = true;
        Scanner scMain = new Scanner(System.in); // 统一使用一个Scanner,避免资源问题

        do {
            playGuess();
            System.out.println("想再玩一次吗?Y/N");
            String answer = scMain.nextLine().trim();
            playAgain = answer.equalsIgnoreCase("y");
        } while (playAgain);
        
        scMain.close();
    }
}

关键细节说明

  1. 统一使用nextLine()读取输入:避免使用nextInt()后残留的换行符导致后续读取异常,同时能完整捕获用户输入的字符串指令
  2. 异常处理:用try-catch捕获NumberFormatException,处理用户输入非数字且非quit的情况,提示后继续循环
  3. 退出逻辑优先级:先判断是否为quit指令,再处理数字输入,保证退出指令能被及时识别
  4. 资源优化:main方法中统一创建一个Scanner对象,避免多次创建造成的资源浪费

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:43:21