我正在尝试使用do-while循环在Java中创建剪刀石头布游戏。计算机将随机选择1,用户进行选择。退出条件是如果用户赢了两次(userWin
)或计算机赢了两次(compWin
)。如果平局,双方计数器均不增加。
// Scissors, paper, stone game. Best of 3.
// scissors = 0; paper = 1; stone = 2;
import java.util.Scanner;
public class Optional2 {
public static void main(String[] args) {
int userWin = 0;
int compWin = 0;
do {
//comp choice
int comp = 1; //TEST CASE
// int comp = (int) (Math.random() * (2 - 0 + 1) + 0);
//user choice
System.out.println("0 for scissors, 1 for paper, 2 for stone");
Scanner sc = new Scanner(System.in);
int user = sc.nextInt();
//Draw
if (comp == user) {
System.out.println("Draw");
//Win =)
} else if (comp == 0 && user == 2 || comp == 1 && user == 0 ||
comp == 2 && user == 1) {
System.out.println("WIN!");
userWin++;
//Lose =(
} else {
System.out.println("Lose =(");
compWin++;
}
} while (compWin < 2 || userWin < 2);
System.out.println("You won " + userWin + " times!");
}
}
对于变量
int comp
而言,应该是随机的,但是出于方便测试,我将其设置为1(paper)。然而,目前只有当满足第一个条件时才会退出循环。如果使用
||
运算符来使第二个条件成立时也退出循环,但实际上循环仍然会继续。例如,如果我写成
while (userWin < 2 || compWin < 2)
,那么当用户胜利两次时就会退出循环,但是当电脑胜利两次时却不会退出循环。如果我写成while (compWin < 2 || userWin < 2)
,那么当电脑胜利两次时就会退出循环,但是当用户胜利两次时却不会退出循环。我尝试改成
while ((userWin < 2) || (compWin < 2))
,但并没有起到作用。
compWin
和userWin
都大于等于 2 时才停止? - Alderath