0

0

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

碧海醫心

碧海醫心

发布时间:2025-09-11 22:11:01

|

589人浏览过

|

来源于php中文网

原创

修复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已经被用作格式化的数值。

    歌者PPT
    歌者PPT

    歌者PPT,AI 写 PPT 永久免费

    下载

    正确的做法是使用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初学者更好地理解和掌握循环控制和字符串格式化的相关知识。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

1031

2023.08.02

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

887

2023.07.31

python中的format是什么意思
python中的format是什么意思

python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

463

2024.06.27

printf用法大全
printf用法大全

php中文网为大家提供printf用法大全,以及其他printf函数的相关文章、相关下载资源以及各种相关课程,供大家免费下载体验。

76

2023.06.20

fprintf和printf的区别
fprintf和printf的区别

fprintf和printf的区别在于输出的目标不同,printf输出到标准输出流,而fprintf输出到指定的文件流。根据需要选择合适的函数来进行输出操作。更多关于fprintf和printf的相关文章详情请看本专题下面的文章。php中文网欢迎大家前来学习。

306

2023.11.28

java中break的作用
java中break的作用

本专题整合了java中break的用法教程,阅读专题下面的文章了解更多详细内容。

120

2025.10.15

java break和continue
java break和continue

本专题整合了java break和continue的区别相关内容,阅读专题下面的文章了解更多详细内容。

261

2025.10.24

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

760

2023.08.03

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 4.4万人学习

C# 教程
C# 教程

共94课时 | 11.3万人学习

Java 教程
Java 教程

共578课时 | 81.7万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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