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个循环,它就会说“密码不正确”,然后就会崩溃。而不是“最大尝试次数”消息。
发布于 2017-01-16 05:38:47
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else {
System.out.println("You got it right!");
break;
}
if((input == 5) && (!password.equals("bluesky123"))) {
System.out.println("maximum number of attempts reached");
break;
}
} 你的逻辑有一些缺陷。您必须注意JAVA如何处理if / else if
https://www.tutorialspoint.com/java/if_else_statement_in_java.htm
发布于 2017-01-16 05:36:59
请允许我注释:
将始终计算此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)。
发布于 2017-01-16 05:36:48
我测试了你的代码,它正在工作!您唯一需要做的就是将下面的代码行移到while循环中
System.out.println("What is the password?");这样做,它将打印“不正确的密码”,然后将再次打印“密码是什么?”
因为在它现在工作的方式下,软件似乎不会等待密码被重新输入,而实际上它是。
https://stackoverflow.com/questions/41666512
复制相似问题