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

    修改后的代码示例:

    立即学习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已经被用作格式化的数值。

    TapNow
    TapNow

    新一代AI视觉创作引擎

    下载

    正确的做法是使用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
java

Java是一个通用术语,用于表示Java软件及其组件,包括“Java运行时环境 (JRE)”、“Java虚拟机 (JVM)”以及“插件”。php中文网还为大家带了Java相关下载资源、相关课程以及相关文章等内容,供大家免费下载使用。

834

2023.06.15

java正则表达式语法
java正则表达式语法

java正则表达式语法是一种模式匹配工具,它非常有用,可以在处理文本和字符串时快速地查找、替换、验证和提取特定的模式和数据。本专题提供java正则表达式语法的相关文章、下载和专题,供大家免费下载体验。

738

2023.07.05

java自学难吗
java自学难吗

Java自学并不难。Java语言相对于其他一些编程语言而言,有着较为简洁和易读的语法,本专题为大家提供java自学难吗相关的文章,大家可以免费体验。

734

2023.07.31

java配置jdk环境变量
java配置jdk环境变量

Java是一种广泛使用的高级编程语言,用于开发各种类型的应用程序。为了能够在计算机上正确运行和编译Java代码,需要正确配置Java Development Kit(JDK)环境变量。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

397

2023.08.01

java保留两位小数
java保留两位小数

Java是一种广泛应用于编程领域的高级编程语言。在Java中,保留两位小数是指在进行数值计算或输出时,限制小数部分只有两位有效数字,并将多余的位数进行四舍五入或截取。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

398

2023.08.02

java基本数据类型
java基本数据类型

java基本数据类型有:1、byte;2、short;3、int;4、long;5、float;6、double;7、char;8、boolean。本专题为大家提供java基本数据类型的相关的文章、下载、课程内容,供大家免费下载体验。

446

2023.08.02

java有什么用
java有什么用

java可以开发应用程序、移动应用、Web应用、企业级应用、嵌入式系统等方面。本专题为大家提供java有什么用的相关的文章、下载、课程内容,供大家免费下载体验。

430

2023.08.02

java在线网站
java在线网站

Java在线网站是指提供Java编程学习、实践和交流平台的网络服务。近年来,随着Java语言在软件开发领域的广泛应用,越来越多的人对Java编程感兴趣,并希望能够通过在线网站来学习和提高自己的Java编程技能。php中文网给大家带来了相关的视频、教程以及文章,欢迎大家前来学习阅读和下载。

16926

2023.08.03

高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

9

2026.01.16

热门下载

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

精品课程

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

共23课时 | 2.6万人学习

C# 教程
C# 教程

共94课时 | 6.9万人学习

Java 教程
Java 教程

共578课时 | 46.7万人学习

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

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