我正在为类做分配,并希望创建一个循环,给用户3次登录的机会,输入正确的用户名和密码。
下面是我代码的一部分:
System.out.println("Enter password");
String inputPassword = input.next();
int count = 0;
//create while loop, set loop continuation condition to count < 3
while (count <= 2) {
if ((!inputUsername.equals(userName)) || (!inputPassword.equals(password))) {
System.out.println("Wrong entry. try again: Enter username");
inputUsername = input.next();
System.out.println("Enter password");
inputPassword = input.next();
}
else
System.out.println("You are now logged in");
count++;
break;
}
if (count > 2)
System.out.println("You have enterede wrong three times. Please try again in a few hours");
System.exit(0);知道为什么系统在两次尝试失败后退出而没有给我错误消息“您输入了错误三次(.)”吗?
我认为问题在于增加计数后的“中断”,但不确定。
如果没有此中断,如果输入成功,控制台将显示“您现在登录”3次,然后显示错误消息“您输入了错误的三次(.)”--这就是我为什么这么说的原因。
发布于 2017-09-13 14:20:02
你的break是无条件的。它将始终运行,这意味着您的循环将始终退出第一次迭代。
前两个失败的尝试都发生在第一次迭代之前和期间,然后单击break并退出。但是,由于您从未循环过,所以count只增加一次,就在中断之前。
我相信您打算使用大括号将break分组到else下。现在,由于您没有使用大括号,所以只有println语句是else的一部分。从不省略的大括号。
发布于 2017-09-13 14:27:58
谢谢卡西根!
这事儿可以理解!
与此同时,我找到了一个解决办法。我已经改变了继续的条件,它是有效的!
int count = 0;
//create while loop, set loop continuation condition to count <2
while (count < 2 && ((!inputUsername.equals(userName)) || (!inputPassword.equals(password)))) {
System.out.println("Wrong entry. try again: Enter username");
inputUsername = input.next();
System.out.println("Enter password");
inputPassword = input.next();
count++;
}
if ((inputUsername.equals(userName)) && (inputPassword.equals(password)))
System.out.println("You are now logged in");
else
System.out.println("You have enterede wrong three times. Please try again in a few hours");
System.exit(0);再次感谢!
发布于 2017-09-13 14:57:56
你的“休息”需要移动。
System.out.println("Enter password");
String inputPassword = input.next();
int count = 0;
//create while loop, set loop continuation condition to count < 3
while (count <= 2) {
if ((!inputUsername.equals(userName)) || (!inputPassword.equals(password))) {
System.out.println("Wrong entry. try again: Enter username");
inputUsername = input.next();
System.out.println("Enter password");
inputPassword = input.next();
}
else {
System.out.println("You are now logged in");
break;
}
count++;
}
if (count > 2)
System.out.println("You have entered wrong three times. Please try again in a few hours");
System.exit(0);https://stackoverflow.com/questions/46199788
复制相似问题