我正在尝试将最大登录尝试次数限制为3.但是,我的代码会在用户有机会再次按下登录按钮之前使用所有尝试。我该如何解决这个问题?
private void executeLogin() {
String userNameStr = userNameTF.getText();
String passWordStr = passWordTF.getText();
int totalAttempts = 3;
while (totalAttempts != 0) {
if (userNameStr == "temp" && passWordStr == "pass") {
System.out.println("Login Correct!");
return;
} else {
System.out.println("Incorrect Login");
totalAttempts--;
System.out.println(totalAttempts);
}
}
if (totalAttempts == 0) {
System.out.println("Maximum number of attempts exceeded");
}
}
答案 0 :(得分:1)
因此,您的代码存在3个主要问题:
您使用while循环 - 虽然您根本不应该循环,但每次按下登录按钮时都应调用函数。
尝试次数不能是局部变量 - 您应该保留其值以供将来使用(那么全局变量)
您正在以错误的方式比较字符串(不是==
而是equals
)
public class MyForm extends ... {
int totalAttempts = 3;
private void login() {
String userNameStr = userNameTF.getText();
String passWordStr = passWordTF.getText();
if (totalAttempts != 0)
if ("temp".equals(userNameStr) && "pass".equals(passWordStr))
System.out.println("Correct");
else {
System.out.println("Incorrect");
totalAttempts--;
}
else
System.out.println("Maximum number of attempts exceeded");
}
}
答案 1 :(得分:1)
每当调用executeLogin()时,totalAttempts的先前值将被删除,并且它将再次初始化为3.要控制它,可以将totalAttempts设为全局 `int totalAttempts = 3; private void executeLogin(){
String userNameStr = userNameTF.getText();
String passWordStr = passWordTF.getText();
if (totalAttempts != 0) {
if (userNameStr == "temp" && passWordStr == "pass") {
System.out.println("Correct");
else {
System.out.println("Incorrect");
totalAttempts--;
} else {
System.out.println("Maximum number of attempts exceeded");
}
}`或者如果你在类中声明它使它静止。
答案 2 :(得分:0)
你的问题是while循环不等待用户再次按下按钮。假设每次按下按钮时都会调用executeLogin(),你需要保持一个全局尝试变量,并在每次调用方法时减少它,而不是在同一个调用中多次。
{{1}}
答案 3 :(得分:0)
您的代码只执行相同的登录totalAttempts
次。你不放弃控制权。在事件驱动编程中,您不必等待用户执行某些操作,您可以设置它并执行操作以响应用户执行某些操作。换句话说,您永远不会编写主动等待用户再次输入密码的代码。
最重要的是,没有“将登录次数限制为3”这样的事情。您可以将连续不正确登录的数量限制为3,可以将连续不正确的用户登录的数量限制为3,可以限制错误登录的次数每个周期到3 - 所有这些都需要一些数据结构来保存有关失败登录的信息。
答案 4 :(得分:0)
您的代码中的问题是您没有请求用户再次输入他的用户名和密码。我的修复是:
设计函数,以便它在循环中请求凭证
private void executeLogin() {
String userNameStr;
String passWordStr;
int totalAttempts = 3;
while (totalAttempts != 0) {
userNameStr = userNameTF.getText();
passWordStr = passWordTF.getText();
if (userNameStr == "temp" && passWordStr == "pass") {
System.out.println("Login Correct!");
return;
} else {
System.out.println("Incorrect Login");
totalAttempts--;
System.out.println(totalAttempts);
}
}
if (totalAttempts == 0) {
System.out.println("Maximum number of attempts exceeded");
}
}