[英]Can't check string value
我正在尝试检查是否包含一个字符串值,但它始终在输入else,这是什么问题? 谢谢
public void alertBtn(View v){
EditText text = (EditText)findViewById(R.id.editText1);
String value = text.getText().toString();
String password="asd";
if (value==password){
new AlertDialog.Builder(this)
.setTitle("Success")
.setMessage("Correct Password")
.setNeutralButton("OK", null)
.show();
}
else
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("Wrong password")
.setNeutralButton("OK", null)
.show();
}
使用==运算符将比较字符串的引用而不是字符串本身。
String value = text.getText().toString();
String password="asd";
if (value.equals(password))
{
}
使用.equals
或.equalsIgnoreCase()
比较字符串
if (value.equals(password)){
还将editText的初始化移动到onCreate
。 单击按钮时无需每次都初始化edittext
text = (EditText)findViewById(R.id.editText1); // in onCreate
并将EditText text
声明为类成员
使用equals()函数
尝试
if( value.equals(password) ) {
}
看这里
使用String.equals(String other)
函数比较字符串,而不是==
运算符。
该函数检查字符串的实际内容, ==
运算符检查对对象的引用是否相等。 请注意,字符串常量通常是“ interned”的,因此实际上可以将具有相同值的两个常量与==
进行比较,但最好不要依赖于此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.