如果条件被忽略并且它总是跳转到else语句

时间:2018-11-06 07:50:39

标签: java android

我是android的初学者,这可能很简单,但我无法弄清楚

public void login (View view){
    EditText et = (EditText) findViewById(R.id.txtUserName);
    String text= et.getText().toString();
    System.out.println("text = "+text);

    if(text.matches("User")){
        System.out.println("Im in if");
        Intent intent = new Intent(this, Order.class);
        startActivity(intent);

    }else if(text.matches("HOD")){

        Intent intent = new Intent(this,HOD.class);
        startActivity(intent);

    }else if(text.matches("HR")) {

        Intent intent = new Intent(this,HR.class);
        startActivity(intent);

    }else{

        System.out.println("Im in else");

    }

}  

if语句不起作用,并且总是跳转到else语句

2 个答案:

答案 0 :(得分:2)

方法matches()期望使用正则表达式作为参数。但是您要检查字符串是否相同。因此,您应该使用if(text.equals(""))而不是matches("")

答案 1 :(得分:0)

尝试使用此代码,因为matches func用于正则表达式

 public void login (View view){
            EditText et = (EditText) findViewById(R.id.txtUserName);
            String text= et.getText().toString();
            System.out.println("text = "+text);

            if(text.equals("User")){//if you want exact value otherwise you can use text.equalsIgnoreCase("your string")
                System.out.println("Im in if");
                Intent intent = new Intent(this, Order.class);
                startActivity(intent);

            }else if(text.equals("HOD")){

                Intent intent = new Intent(this,HOD.class);
                startActivity(intent);

            }else if(text.equals("HR")) {

                Intent intent = new Intent(this,HR.class);
                startActivity(intent);

            }else{

                System.out.println("Im in else");

            }

        }