Java 登录帐户在输入时不工作
由于某些原因,我设置为登录的帐户无法工作。即使在输入信息时所有内容都正确键入。我不知道这为什么不起作用。我的循环工作正常,在告诉我已尝试的最大尝试次数之前,它给了我3次尝试。任何帮助都会很好Java 登录帐户在输入时不工作,java,Java,由于某些原因,我设置为登录的帐户无法工作。即使在输入信息时所有内容都正确键入。我不知道这为什么不起作用。我的循环工作正常,在告诉我已尝试的最大尝试次数之前,它给了我3次尝试。任何帮助都会很好 package authenticationprogram; import java.util.Scanner; public class AuthenticationProgram { public static void main(String[] args) { Scan
package authenticationprogram;
import java.util.Scanner;
public class AuthenticationProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //this reads the input from the user
String username, password;
int totalAttempts = 3; //sets the total attempts for login to 3
while (totalAttempts != 0) {
System.out.print("Enter username: ");
username = scan.nextLine();
System.out.print("Enter password: ");
password = scan.nextLine();
if (username.equals("griffin.keyes") && (password.equals("alphabetsoup"))){ // sets accounts for login
if (username.equals("rosario.dawson") && (password.equals("animaldoctor")))
if (username.equals("bernie.gorilla") && (password.equals("secretpassword")))
if (username.equals("donald.monkey") && (password.equals("M0nk3ybusiness")))
if (username.equals("jerome.grizzlybear") && (password.equals("grizzly1234")))
if (username.equals("bruce.grizzlybear") && (password.equals("letmein")))
System.out.println("Access Granted! Welcome!"); // shows user they entered the correct information
return;
} else {
System.out.println("Incorrect Login Information!"); // shows user they entered the wrong information
totalAttempts--;
System.out.println(totalAttempts);
}
}
if (totalAttempts == 0) {
System.out.println("Maximum number of attempts exceeded"); //Tells the user they tried more than 3 times to login.
}
}
}
您正在使用嵌套的
if
条件,这些条件永远不会变为true
,您需要使用else if
,如下所示:
if (username.equals("griffin.keyes") && (password.equals("alphabetsoup"))){
System.out.println("Access Granted! Welcome!");
return;
} else if(username.equals("rosario.dawson") && (password.equals("animaldoctor"))) {
System.out.println("Access Granted! Welcome!");
return;
} else if(...) {
//add other else if conditions
} else {
System.out.println("Incorrect Login Information!");
totalAttempts--;
System.out.println(totalAttempts);
}
我强烈建议您使用
HashMap
(查看)存储用户名和密码,这样您就不需要太多的,如果出现条件。欢迎使用堆栈溢出!看起来您需要学习使用调试器。请随便吃点。如果您以后仍然有问题,请随时回来用一个演示您的问题的示例。您可能想先看看为什么要嵌套六层的If
语句。如何设置帐户?虽然这不一定会导致问题,但我建议将您的循环更改为do While
风格,因为您保证至少迭代一次。谢谢您的帮助!我将用elseif语句设置它们。如果有任何错误,我会保留{else{system..out.println(“错误登录”);