所以我有一个非常非常基本的登录程序,只需在输入正确的凭据时打印一行。即使我输入正确的凭据,它所做的就是从我的if else语句中打印错误消息。任何帮助将不胜感激。
import java.util.Scanner;
public class Exercise4
{
private static String Username = "javacave";
private static String Password = "welcome1";
public static void main(String[] args)
{
System.out.println("Please enter username");
Scanner in = new Scanner(System.in);
String UN = in.nextLine();
System.out.println("Please enter password");
Scanner inn = new Scanner(System.in);
String PW = inn.nextLine();
if (UN == Username && PW == Password)
{
System.out.println("User has logged in successfully!");
}
else {
System.out.println("You have entered the wrong credentials, please try again.");
}
}
}
答案 0 :(得分:2)
(UN == Username && PW == Password)
应该是:
(UN.equals(Username) && PW.equals(Password))
每当比较两个字符串时,使用equals()
检查值的相等性,而不是使用==
来检查内存中两个引用是否相同。
答案 1 :(得分:0)
Scanner scan = new Scanner(System.in);
String userName = scan.nextLine();
String pass = scan.nextLine();
if(userName.equals("123") && pass.equals("123"))
{
System.out.println("Logged!");
}
else
{
System.out.println("Error!");
}