您好我正在编写一个用户输入的简单用户名/密码,但是我的代码绕过所有if / if else语句并转到else语句。我不确定我的语法是否不正确或者使用if / else语句是否不正确。或者如果我只是编码错了。请帮忙!
import java.util.Scanner;
public class Passwords
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] username = {"admin1", "admin2", "admin3", "admin4", "admin5"};
String[] password = {"pass1", "pass2", "pass3", "pass4", "pass5"};
System.out.println("Please enter in one of the following usernames : admin1, admin2, admin3, admin4, or admin5");
String userinput = input.nextLine();
System.out.println("Please enter in the password corresponding to your username: pass1, pass2, pass3, pass4, or pass5");
String passinput = input.nextLine();
if (userinput == username[0] && passinput == password[0])
{
System.out.println("Access granted!");
}
else if (userinput == username[1] && passinput == password[1])
{
System.out.println("Access granted!");
}
else if (userinput == username[2] && passinput == password[2])
{
System.out.println("Access granted!");
}
else if (userinput == username[3] && passinput == password[3])
{
System.out.println("Access granted!");
}
else if (userinput == username[4] && passinput == password[4])
{
System.out.println("Access granted!");
}
else
{
System.out.println("Sorry the username or password you entered is incorrect. Please try again");
System.out.println("Please enter in one of the following usernames : admin1, admin2, admin3, admin4, or admin5");
String userinput1 = input.next();
System.out.println("Please enter in the password corresponding to your username: pass1, pass2, pass3, pass4, or pass5");
String passinput1 = input.next();
if (userinput1 == username[0] && passinput1 == password[0])
{
System.out.println("Access granted!");
}
else if (userinput1 == username[1] && passinput1 == password[1])
{
System.out.println("Access granted!");
}
else if (userinput1 == username[2] && passinput1 == password[2])
{
System.out.println("Access granted!");
}
else if (userinput1 == username[3] && passinput1 == password[3])
{
System.out.println("Access granted!");
}
else if (userinput1 == username[4] && passinput1 == password[4])
{
System.out.println("Access granted!");
}
else
{
System.out.println("Sorry, your username/password does not match our database. Contact the administrator.");
}
}
}
}
答案 0 :(得分:0)
use,userinput.equals(username[0])
//这将比较字符串值
在java ==
中将比较对象id'如果它们是不同的对象,它将始终为false。
答案 1 :(得分:0)
在Java中,正在使用字符串比较string1.equals(string2)
。
答案 2 :(得分:0)
使用String类的equals()方法进行比较
userinput == username[0] to userinput.equals(username[0])
== tests for reference equality.
.equals() tests for value equality.
例如:
new String(userinput).equals(username[0]) // --> true
new String(userinput) == username[0] // --> false
new String(userinput) == new String(username[0]) // --> false