问题描述
从这里开始,我正在创建一个非常简单的“登录”样式程序,目前我使用if语句来查看用户输入的内容是否与我已经声明的内容匹配,如果输入正确,他们将获得“登录”消息,如果不是,则程序终止。
但是,我希望这样做,以便用户在终止之前最多可以尝试3次以获取正确的凭据。 我将如何去做呢?
List<String> usernames = accessClass.setUsernames();
List<String> passwords = accessClass.setPasswords();
System.out.print("Please enter your username: ");
user1 = wordScan.next();
if(usernames.contains(user1)){
System.out.print("Now enter your password: ");
pass1=wordScan.next();
if(passwords.contains(pass1)){
System.out.println("Logged in.");
System.out.println("Your username is "+user1);
random.setSeed(System.currentTimeMillis());
numGen = random.nextInt(899999)+100000;
System.out.println("Your access code is: "+numGen);
}
}else{
System.out.println("Invalid Username... Terminating.");
System.exit(0);
}
wordScan.close();
}
非常感谢
1楼
我还将使用这样的循环:
List<String> usernames = accessClass.setUsernames();
List<String> passwords = accessClass.setPasswords();
while(attempts > 0 && !loggedIn) {
System.out.print("Please enter your username: ");
user1 = wordScan.next();
int attempts = 3;
boolean loggedIn = false;
attempts = attempts -1;
if(usernames.contains(user1)){
System.out.print("Now enter your password: ");
pass1=wordScan.next();
if(passwords.contains(pass1)){
System.out.println("Logged in.");
System.out.println("Your username is "+user1);
loggedIn = true;
random.setSeed(System.currentTimeMillis());
numGen = random.nextInt(899999)+100000;
System.out.println("Your access code is: "+numGen);
}
}
}
if(!loggedIn) {
System.out.println("Invalid Username or password... Terminating.");
System.exit(0);
}
wordScan.close();
}
2楼
如果您最多要循环3次,则可以执行以下操作:
for (int i = 0; i<3; i++)
{
... your code
// when username + password match : use break; at the end in order not to do the remaining loops
}
3楼
for
或while
循环也足够了,如果您的用户和密码数组已链接在一起(user1具有pass1,user2具有pass2等),则可以使用indexOf
获取列表中的索引并比较两者:
if(usernames.contains(user1)){
System.out.print("Now enter your password: ");
for(int i = 0; i < 3; i++){
pass1 = wordScan.next();
if(passwords.contains(pass1)
&& usernames.indexOf(user1) == passwords.indexOf(pass1)){
// correct
break;
} else if (i == 2){
// incorrect and end of try
}
}
}
4楼
试试这个代码:
List<String> usernames = accessClass.setUsernames();
List<String> passwords = accessClass.setPasswords();
System.out.print("Please enter your username: ");
user1 = wordScan.next();
int i=0;
while(i<3)
{
if(usernames.contains(user1)){
System.out.print("Now enter your password: ");
pass1=wordScan.next();
if(passwords.contains(pass1)){
System.out.println("Logged in.");
System.out.println("Your username is "+user1);
random.setSeed(System.currentTimeMillis());
numGen = random.nextInt(899999)+100000;
System.out.println("Your access code is: "+numGen);
break;
}
}else{
if(i==2) {
System.out.println("Invalid Username... Terminating.");
System.exit(0);
}
else {
System.out.println("Invalid Username... Try Again.");
i++;
}
}
}
wordScan.close();
}