我正在为一个玩家和计算机正在玩游戏的课程编写程序。游戏包括挑选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)为假时,如何在System.out.println之后跳过这些行(&#34;你选择了最后一根火柴......你丢了!! !&#34);?在条件满足后有没有办法打破中间循环?或者我的逻辑是完全错误的?
答案 0 :(得分:1)
您可以从方法return
main
...
if (total == 21) {
System.out.println("You picked the last matchstick... YOU LOSE!!!");
return;
}
...
答案 1 :(得分:0)
你的逻辑完全错了.bcz已经让你的电脑选择了 根据玩家值的值。每次都由玩家开始。所以每次玩家选择一个值然后计算机。每次总时间= 5。
{!terms f=uniqueId}1000,1001,10002,10003
然后玩家必须玩。所以玩家每次都会失败。
当while循环的条件(总计<21)为假时?试试这个。
ex: player play 4 times + computer play 4 times : total =20
但计算机永远胜利