Java ==!=&& ||运营商?

时间:2016-08-30 14:05:24

标签: java

我的代码有问题。此代码应检查登录名和密码。问题是else if语句显示错误的输出。例如,当我输入用户名== admin和密码== 1234时,显示用户名不正确。

import java.io.*;

public class login 
{
public static void main(String [] args) throws IOException
{
    String username = "admin"; 
    String password = "123";

    BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));

    System.out.print("Enter username : ");
    username = inData.readLine();

    System.out.print("Enter password : ");
    password = inData.readLine();

    if((username == "admin") && (password == "123"))
    {
        System.out.println("Welcome " + username + "\n*** Login Sucessfully ***" + "\n*** Access Granted ***");
    }
    else if((username != "admin") && (password == "123"))
    {
        System.out.println("Sorry, username is incorrect!\n*** Access Denied ***");
    }
    else if((username == "admin") && (password != "123"))
    {
        System.out.println("Sorry, password is incorrect!\n*** Access Denied ***");
    }
    else if((username != "admin") && (password != "123"))
    {
        System.out.println("Sorry, username and password is incorrect!\n*** Access Denied ***");
    }
}
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,

.equals()方法用于比较字符串。 username.equals("admin"),它将变量username的值与值“admin”进行比较,这里都是字符串

相关问题