【发布时间】:2019-11-21 17:01:04
【问题描述】:
我正在尝试制作“密码破解者”。用户尝试猜测随机密码(4 位整数) 程序说如果输入的密码太低/太高/等于。但是我卡住了,我不知道为什么我的循环不会结束。
public static void main(String[] args) {
int password = 1234;
startGame(checkNumber(loadNumber(),password));
}
public static void startGame(boolean isAWinner) {
int lives = 5;
do {
loadNumber();
lives--;
} while (lives > 0 || !isAWinner); //has lives or is not a winner
}
public static int loadNumber() {
System.out.println("Type the number");
Scanner scan = new Scanner(System.in);
int givenNumber = scan.nextInt();
return givenNumber;
}
//check if greater,lower or equal
public static boolean checkNumber(int number, int password) {
boolean isAWinner = false;
if (number == password) {
System.out.println("congratulations");
isAWinner = true;
}
if (number > password) {
System.out.println("too much");
}
if (number < password) {
System.out.println("too little");
}
return isAWinner;
}
【问题讨论】:
-
当 living == 0 AND isAWinner == TRUE 时,循环将结束。这可能不是您想要的 - 如果您希望用户最多尝试 5 次,请使用 &&。