首页 > Java > java教程 > 正文

修复Java掷骰子游戏中的循环中断异常

碧海醫心
发布: 2025-09-11 22:11:01
原创
579人浏览过

修复java掷骰子游戏中的循环中断异常

本文旨在帮助Java初学者解决在掷骰子游戏中循环中断时遇到的异常问题。通过分析代码,找出导致异常的原因,并提供修改后的代码示例,确保游戏在玩家选择退出或资金不足时能够正常结束,并展示游戏结束时的信息。

在提供的代码中,主要问题集中在游戏循环的退出条件和System.out.printf的使用上。以下将详细解释并提供修改后的代码。

问题分析与修复

  1. 循环退出条件

    原代码中,循环的退出条件是playAgain && total > 0。这意味着只有当playAgain为true且total大于0时,循环才会继续。虽然在循环内部有break语句用于处理total <= 9和again.equalsIgnoreCase("n")的情况,但逻辑上没有错误。 问题在于,当输入无效字符时,again变量的值未被正确更新,导致可能进入死循环。

    修改后的代码示例:

    立即学习Java免费学习笔记(深入)”;

    while (playAgain && total > 0) {
        // ... (游戏逻辑) ...
    
        if (total <= 9) {
            break;
        }
    
        System.out.println("Keep playing (y/Y or n/N)? ");
        in.nextLine(); // Consume the newline character
        String again = in.nextLine();
    
        if (again.equalsIgnoreCase("y")) {
            playAgain = true;
        } else if (again.equalsIgnoreCase("n")) {
            playAgain = false; // Set playAgain to false to exit the loop
            break;
        } else {
            System.out.println("Invalid character input, try again:");
            // No need to read input again here. The loop will continue and ask again.
        }
    }
    登录后复制

    注意事项:

    • 在读取字符串之前,使用in.nextLine()来消耗掉之前in.nextInt()留下的换行符,避免影响后续的输入。
    • 当玩家输入 "n" 时,将 playAgain 设置为 false,确保循环能够正常退出。
    • 当输入无效字符时,不需要再次读取输入。循环会自动回到开始,再次提示用户输入。
  2. System.out.printf 异常

    原始代码中使用System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);,这可能会导致MissingFormatArgumentException异常,因为%.2%需要一个参数,而winPercent已经被用作格式化的数值。

    百度文心百中
    百度文心百中

    百度大模型语义搜索体验中心

    百度文心百中 22
    查看详情 百度文心百中

    正确的做法是使用System.out.println进行字符串拼接,或者使用String.format方法。

    修改后的代码示例:

    立即学习Java免费学习笔记(深入)”;

    // 方法一:使用 System.out.println 进行字符串拼接
    System.out.println("Based on your play, the probability of winning is " + String.format("%.2f", winPercent) + "%.");
    
    // 方法二:使用 String.format
    //System.out.printf("Based on your play, the probability of winning is %.2f%%", winPercent);
    登录后复制

    解释:

    • 方法一使用 String.format("%.2f", winPercent) 将 winPercent 格式化为保留两位小数的浮点数,然后与字符串拼接。
    • 方法二使用 String.format 和 %% 来输出百分号。

完整修改后的代码

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

public class GameOfCrapsTester {

    static Scanner in = new Scanner(System.in);
    static Random rand = new Random();

    public static void main(String[] args) {

        System.out.println("Welcome to the game of Craps");
        System.out.println(" ");
        System.out.println("The house has given you a starting balance of $500");
        System.out.println("On each round, you will make a whole number wager.");
        System.out.println("The minimum wager is $10, and the maximum wager is your remaining balance.");
        System.out.println(" ");
        System.out.println("You may keep playing until you decide to cash in, or");
        System.out.println("    you can't cover the minimum wager.");
        System.out.println("Good Luck!");

        boolean win;
        double wins = 0, numOfGames = 0;
        int total = 500;

        // Come out roll and set point value
        int pointValue = 0;
        boolean playAgain = true;
        while (playAgain && total > 0) {
            System.out.println(" ");
            System.out.println("Your balance is $" + total);
            System.out.println(" ");
            System.out.println("Place your bet: $");

            // Get and check wager placed
            int bet = in.nextInt();
            in.nextLine(); // Consume newline
            while (bet > total || bet < 10) {
                if (bet < 10) {
                    System.out.println("Bet must be larger than $10.");
                }
                System.out.println("I'm sorry, that's not a valid wager; please re-enter: ");
                bet = in.nextInt();
                in.nextLine(); // Consume newline
            }
            int num = rollDice();
            if ((num >= 4 && num <= 10 && num != 7) || num == 0) {
                pointValue = num;
                System.out.println(" ");
                System.out.println("Your point value is " + pointValue);
                System.out.println(" ");
                win = rollWithPoint(pointValue);

                if (win) {
                    total = wonGame(bet, total);
                    wins++;
                    numOfGames++;
                    System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
                } else if (!win) {
                    total = lostGame(bet, total);
                    numOfGames++;
                    System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
                }
            } else if (num == 7 || num == 11) {
                total = wonGame(bet, total);
                wins++;
                numOfGames++;
                System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
            } else {
                total = lostGame(bet, total);
                numOfGames++;
                System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
            }

            if (total <= 9) {
                break;
            }

            System.out.println("Keep playing (y/Y or n/N)? ");
            String again = in.nextLine();

            if (again.equalsIgnoreCase("y")) {
                playAgain = true;
            } else if (again.equalsIgnoreCase("n")) {
                playAgain = false;
                break;
            } else {
                System.out.println("Invalid character input, try again:");
            }
        }// end of loop

        gameOver(wins, numOfGames);

    } // END of main

    public static int rollDice() {

        int dice1, dice2, total;
        dice1 = rand.nextInt(6) + 1;
        dice2 = rand.nextInt(6) + 1;
        total = dice1 + dice2;
        System.out.print("Your roll: ");
        System.out.print("Dice1: " + dice1);
        System.out.print(", Dice2: " + dice2);
        System.out.println("; Roll Value: " + total);
        return total;

    } // END of rollDice

    public static boolean rollWithPoint(int point) {

        int total = rollDice();
        boolean winner = false;
        while (total != 7 && winner == false) {
            total = rollDice();
            if (total == point) {
                winner = true;
            } else {
                winner = false;
            }
        }
        return winner;
    } // END of rollWithPoint

    public static int lostGame(int bet, int total) {

        System.out.println("Oh, I'm sorry, you lost.");
        System.out.println(" ");
        total = total - bet;
        System.out.println("Your current balance: $" + total);
        System.out.println(" ");
        return total;

    } // END of lostGame

    public static int wonGame(int bet, int total) {

        System.out.println("A winner!");
        System.out.println(" ");
        total = total + bet;
        System.out.println("Your current balance: $" + total);
        System.out.println(" ");
        return total;

    } // END of wonGame

    public static void gameOver(double win, double tot) {

        double winPercent = (win / tot) * 100;
        System.out.println(" ");
        System.out.println("Based on your play, the probability of winning is " + String.format("%.2f", winPercent) + "%.");
        System.out.println(" ");
        System.out.println("Seems you lost your shirt; better luck next time.");
        System.out.println("Have a nice day! Hope to see you soon!");

    } // END of gameOver

} // END of GameOfCraps
登录后复制

总结

通过以上修改,可以解决游戏循环中断时可能出现的异常,并确保游戏在玩家选择退出或资金不足时能够正常结束。同时,修正了概率输出的格式,使其更加清晰易懂。希望本文能够帮助Java初学者更好地理解和掌握循环控制和字符串格式化的相关知识。

以上就是修复Java掷骰子游戏中的循环中断异常的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号