package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("What is the password?");
Scanner new2 = new Scanner(System.in);
int input = 0;
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
}
}
}
基本上,一旦我完成 5 个循环,它只会显示“密码错误”并中断。不是“最大尝试次数”消息。
最佳答案
请允许我注释一下:
该 if 语句将始终被求值:
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
仅当密码为“bluesky123”时才会评估此 if 语句。在这种情况下,它将始终评估为 true
。
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
在任何情况下都不会计算此 if 语句。一旦 if-else 找到一个正确的语句,它将跳过该部分中的所有其他语句。
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
就您的情况而言,您应该考虑嵌套 if (即一个 if 位于另一个 if 内)。
关于JAVA While 循环 - 最后一个 else if 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666512/