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

如何修改Java骰子游戏代码让重试部分循环,失败时仅需重新输入猜测?

问题根因

你现有代码的问题主要有三点:

  • 姓名输入、骰子随机值生成的逻辑全放在了最外层的游戏总循环里,只要循环重启就会重新要求输入姓名、重新生成骰子数,不符合需求
  • 缺少单局游戏内的猜数循环,现在每轮只能猜一次,猜错后没有停留在当前局让用户重新猜的逻辑
  • 条件判断嵌套错误,猜对的判断逻辑被写在了「猜错」的if分支内部,永远不会被触发

修复方案

调整循环结构和代码块位置:

  1. 把姓名输入、固定常量数组、Scanner实例全部移到最外层总循环外面,全局只初始化一次
  2. 每轮新游戏生成骰子随机值之后,新增内层猜数循环,只要用户没猜对就一直让他重新输入猜的数字,猜对才跳出内层循环
  3. 拆分对错判断逻辑,猜对之后再询问是否要开启新一局

额外修复了原代码的数组越界隐患:原鼓励语数组sorry只有4个元素,骰子随机值范围是0~5,当随机值大于3时会触发数组下标越界报错,修复代码中加了取模运算做兼容。

修复后完整代码

import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main (String[] args) throws IOException {
        // 全局只初始化一次的固定内容
        String[] input = new String[]{"1", "2", "3", "4", "5", "6"};
        String[] sorry = new String[]{"If at first you don't succeed...", "Your luck will improve...", "Don't give up...", "Not this time..."};
        Scanner scan = new Scanner(System.in);
        Random dice = new Random();

        // 只输入一次姓名
        System.out.println( "Hi there, may I please have your name?");
        String name = scan.nextLine();
        System.out.println("What a nice name...");

        boolean run = true;
        // 游戏总循环,控制是否开新局
        while (run) {
            // 每新局生成一次骰子数
            int select = dice.nextInt(input.length);
            System.out.println("ok "+name+", please choose a number between 1 and 6");

            boolean guessedRight = false;
            // 单局猜数循环,猜对才退出
            while (!guessedRight) {
                String play = scan.nextLine();
                System.out.println(input[select]);
                if (!input[select].equals(play)) {
                    // 取模避免数组越界
                    System.out.println(sorry[select % sorry.length] + " try again");
                } else {
                    // 猜对,跳出当前局的猜数循环
                    guessedRight = true;
                    System.out.println("Bingo!!! "+name+" you've won 1 million imaginary dollars!");
                }
            }

            // 猜对后询问是否重开
            System.out.println("would you like to play again \"Y\" or \"N\"");
            String answer = scan.nextLine().toLowerCase();
            if ("n".equals(answer)) {
                System.out.println("Thank you for playing "+name+". Good bye!");
                run = false;
            }
        }
        scan.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:36:03