gpt4 book ai didi

java - 请问,如何让代码在两台计算机或用户获胜后终止

转载 作者:行者123 更新时间:2023-12-01 11:45:22 26 4
gpt4 key购买 nike

请问,如何让我的代码在计算机或用户两次获胜后终止?我被要求编写一个程序来玩流行的剪刀石头布游戏。 (剪刀可以剪布,石头可以敲剪刀,布可以包石头。)程序随机生成数字0、1、2,分别代表剪刀、石头、布。该程序提示用户输入数字 0、1 或 2,并显示一条消息,指示用户或计算机是赢、输还是平局。用户应该继续玩游戏,直到用户或计算机获胜两次以上。不幸的是,代码游戏在两次以上获胜后并没有结束。

谢谢。

 package scissors;
import java.util.Scanner;
public class Scissors {
public static void main(String[] args) {
//generate random number
int count=0;
int computerWin=0;
int youWin= 0;
while (computerWin <2 || youWin<2){
int computer = (int)(Math.random()*3);
// prompt user for input
Scanner s = new Scanner(System.in);
System.out.println("Enter a number; scissor(0),rock(1), paper(2): ");
int you = s.nextInt();

switch(computer){
case 0:
if(you==0){
System.out.println("The computer is scissor and you are scissor. It's a Draw");
}
else if (you==1){
System.out.println("The computer is scissor and you are rock. You won");
youWin++;
}
else if (you==2){
System.out.println("The computer is scissor and you are paper. You lost");
computerWin++;
}
break;
case 1:
if(you==0){
System.out.println("The computer is rock and you are scissor. You lost");
computerWin++;
}
else if (you==1){
System.out.println("The computer is rock and you are rock. It's a Draw");
}
else if(you==2){
System.out.println("The computer is rock and you are paper. You won");
youWin++;
}
break;
case 2:
if (you==0){
System.out.println("The computer is paper and you are scissor. You won");
youWin++;
}
else if (you==1){
System.out.println("The computer is papare and you are rock. You lost");
computerWin++;
}
else if (you==2){
System.out.println("The computer is paper and you are paper. It's a draw");
}
break;
}
if (computerWin>youWin)
System.out.println("Computer wins");
else
System.out.println("You win");
}

}
}

最佳答案

现在,玩家和计算机共享一个计数器。如果玩家获胜,计数器就会上升。如果计算机获胜,它就会下降。这并不跟踪每个人有多少胜利。

您需要一个变量来计算玩家为用户和计算机赢得的胜利次数。

int userPoints = 0, compPoints = 0;

while(userPoints < 2 || compPoints < 2) {
//..
}

if(compPoints > userPoints) {
//computer won
} else {
//user won
}

当计算机获胜时,为 compPoints 添加 1。当用户获胜时,为 userPoints

添加 1

关于java - 请问,如何让代码在两台计算机或用户获胜后终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29184845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com