若条件被忽略,它总是跳转到else语句

  • 本文关键字:语句 else 条件 java 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语句

方法matches()需要一个正则表达式作为参数。但是您要检查字符串是否相同。所以应该使用if(text.equals(""))而不是matches("")

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

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");
}
}  

最新更新