我正在为一个班级编写程序,其中玩家和计算机正在玩游戏。游戏包括挑选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(“您选择了最后一根火柴棒...您输了!!!”)之后的行?满足条件后,有没有办法打破中间循环?还是我的逻辑完全错误?
你可以只return
从方法main
...
if (total == 21) {
System.out.println("You picked the last matchstick... YOU LOSE!!!");
return;
}
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句