我正在尝试使用 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(纸)以便于测试。
但是,目前只有第一个条件为真时才会退出循环。如果 ||
为真,我希望第二个条件也退出循环。运算符,但即使它成立,循环也会继续循环。
即。如果我把 while (userWin < 2 || compWin < 2)
,如果用户赢了两次它会退出,但如果计算机赢了两次则不会。如果我输入 while (compWin < 2 || userWin < 2),如果计算机赢了两次它将退出,但如果用户赢了两次则不会。
我尝试将其更改为 while ((userWin < 2) || (compWin < 2))
也是,但它不起作用。
最佳答案
but the loop just keeps looping even if it comes true
只要条件保持 true
,while
循环就会一直循环。
我认为问题在于您应该将条件重写为:
while ((userWin < 2) && (compWin < 2))
使用 &&
而不是 ||
。事实上:现在 while 循环是这样的:“只要用户没有赢得两次或更多次,并且计算机没有赢得两次或更多次,就继续循环。”
关于Java:具有多个条件的do-while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35777303/