0

所以我有一个非常基本的登录程序,当您输入正确的凭据时,它只会打印一行。即使我输入正确的凭据,它所做的只是从我的 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.");
    }
}
 }
4

2 回答 2

2
(UN == Username && PW == Password)

应该:

(UN.equals(Username) && PW.equals(Password))

每当您在两个字符串之间进行比较时,请使用equals()检查值的相等性,而不是使用==which 检查内存中的两个引用是否相同。

请阅读Java 编程语言的代码约定

于 2013-04-02T22:28:28.683 回答
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!");
}
于 2021-05-22T16:08:01.003 回答