
本文旨在帮助Java初学者解决在掷骰子游戏中循环中断时遇到的异常问题。通过分析代码,找出导致异常的原因,并提供修改后的代码示例,确保游戏在玩家选择退出或资金不足时能够正常结束,并展示游戏结束时的信息。
在提供的代码中,主要问题集中在游戏循环的退出条件和System.out.printf的使用上。以下将详细解释并提供修改后的代码。
问题分析与修复
-
循环退出条件
原代码中,循环的退出条件是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,确保循环能够正常退出。
- 当输入无效字符时,不需要再次读取输入。循环会自动回到开始,再次提示用户输入。
-
System.out.printf 异常
原始代码中使用System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);,这可能会导致MissingFormatArgumentException异常,因为%.2%需要一个参数,而winPercent已经被用作格式化的数值。
正确的做法是使用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初学者更好地理解和掌握循环控制和字符串格式化的相关知识。










