我正在为一个类(class)编写一个程序,其中玩家和计算机正在玩游戏。游戏包括挑选 1、2、3 或 4 根火柴棍。从 21 根棍子中挑出最后一根的玩家就输了。游戏经过精心设计,以便计算机总是获胜。
无论如何,我的问题在于结束游戏的逻辑。这是我的代码:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String player;
int matchstick;
int total = 0;
System.out.println("Rules of the game: \nThe player and computer take turns picking 1, 2, 3 , or 4 matchsticks."
+ " \nThe player to pick the last stick out of 21 loses.");
System.out.print("\nHello player. Please enter your name: ");
player = keyboard.next();
while (total < 21) {
System.out.print("\nHow many matchsticks do you pick, " + player + "? ");
matchstick = keyboard.nextInt();
while (matchstick > 4) {
System.out.print("You have exceeded the limit of 4 matchsticks. Please try again. \n\nHow many matchsticks do you pick? ");
matchstick = keyboard.nextInt();
}
total += matchstick;
System.out.println(player + " has picked " + matchstick + " matchstick(s) and brings the total to " + total + " matchsticks.");
if (total == 21) {
System.out.println("You picked the last matchstick... YOU LOSE!!!");
}
System.out.println("\nNow it's the computer's turn.");
if (matchstick == 1) {
total += 4;
System.out.println("The computer chooses 4 matchsticks, bringing the total to " + total + " matchsticks.");
}
if (matchstick == 2) {
total += 3;
System.out.println("The computer chooses 3 matchsticks, bringing the total to " + total + " matchsticks.");
}
if (matchstick == 3) {
total += 2;
System.out.println("The computer chooses 2 matchsticks, bringing the total to " + total + " matchsticks.");
}
if (matchstick == 4) {
total += 1;
System.out.println("The computer chooses 1 matchstick, bringing the total to " + total + " matchsticks.");
}
}
}
}
当 while 循环的条件(总计 < 21)为 false 时,如何跳过 System.out.println("You picked the last matchstick... YOU LOSE!!!"); 之后的行?有没有办法在满足条件后中断中循环?还是我的逻辑完全错误?
最佳答案
您只需从方法main
返回
...
if (total == 21) {
System.out.println("You picked the last matchstick... YOU LOSE!!!");
return;
}
...
关于java - 玩简单的 Java 游戏时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971960/