1

我目前正在开发一个需要用户输入密码才能访问游戏的应用程序。我有以下 if 语句,但它不起作用,正如您从 if 语句中看到的那样,我尝试了三种不同的方法来使匹配等于 true。

    EditText passInput = (EditText) findViewById(R.id.passwordBox);
    CharSequence Password = passInput.getText();
    RelativeLayout loggedIn = (RelativeLayout) findViewById(R.id.LoggedInLayout);
    RelativeLayout CreateUser = (RelativeLayout) findViewById(R.id.createUserLayout);
    Button loginBtt = (Button) findViewById(R.id.createUser);
    String actualPass = password[x];

    System.out.println(Password + actualPass + passInput);

    if(Password.equals(actualPass)){

        System.out.println("They Matched!");
        loggedIn.setVisibility(View.VISIBLE);
        CreateUser.setVisibility(View.GONE);
        loginBtt.setText("Create User");

    }else if(Password.toString() == actualPass.toString()){

        System.out.println("Second Match");

    }else if(Password == actualPass){

        System.out.println("Third Match");

    }else if(Password.equals(actualPass) == false){

    System.out.println("Wrong");
    incorrectPassword();
    System.out.println(Password);
    System.out.println(actualPass);

    }

当用户注册时,他们需要设置密码。为了测试,我尝试了密码“trst”,但是当插入登录页面时,它返回不正确。这是我的 LogCat 显示的内容:

11-07 11:46:16.357: I/System.out(1998): Wrong
11-07 11:46:16.547: I/System.out(1998): trst
11-07 11:46:16.547: I/System.out(1998): trst

正如您从 LogCat 中看到的,插入的密码和实际密码是相同的,但程序说它们不是!

4

4 回答 4

3

Use .equals() instead of == for checking if one String objects is equal to another. == returns true if two references are referencing the same object, while .equals() returns true if contents of two strings are identical.

于 2013-11-07T12:03:41.037 回答
2

try Password.toString().equals(actualPass.toString())

于 2013-11-07T12:03:33.890 回答
2

您不能使用 .CharSequence与 String 进行比较。因此使用此equal()更改为 StringCharSequence

String Password = passInput.getText().toString();
于 2013-11-07T12:08:19.650 回答
1

Change

 CharSequence Password = passInput.getText();

To

 String Password = passInput.getText().toString();

then

if(Password.equalsIgnorecase(actualPass)){

        System.out.println("They Matched!");
        loggedIn.setVisibility(View.VISIBLE);
        CreateUser.setVisibility(View.GONE);
        loginBtt.setText("Create User");

    }else if(Password.equalsIgnorecase(actualPass.toString())){

        System.out.println("Second Match");

    }else if(Password.equalsIgnorecase(actualPass)){

        System.out.println("Third Match");

    }else if(!Password.equalsIgnorecase(actualPass)){

    System.out.println("Wrong");
    incorrectPassword();
    System.out.println(Password);
    System.out.println(actualPass);

    }
于 2013-11-07T12:03:40.020 回答