比较 Java 中的两个字符串未给出预期结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31017318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:31:38  来源:igfitidea点击:

Comparing two string in Java not giving the expected result

javaandroidstringstring-comparison

提问by A nemati

I am beginner i want to get text in EditTextand compare it with another string .

我是初学者,我想输入文本EditText并将其与另一个字符串进行比较。

I want to check if text writed in EditTextis equals a 'String' then show a Toastbut it is not working

我想检查写入的文本EditText是否等于“字符串”然后显示一个Toast但它不起作用

I debug and check the value of both are exactly admin but if block is not working and shows else block.

我调试并检查两者的值都是 admin 但如果块不起作用并显示 else 块。

if (editText.getText().toString() == "admin") {
    //Never enter this block when i type "admin" in the EditText.
    Toast.makeText(MainActivity.this,"ok",Toast.LENGTH_LONG).show();
} else {
    Toast.makeText(MainActivity.this,"Wrong User Or Pass",
}

采纳答案by Emil

You have to use String.equals()method for string matching.

您必须使用String.equals()方法进行字符串匹配。

Change your code into this

把你的代码改成这个

    if (editText.getText().toString().equals("admin")) {
        //your code
    }

.

.

回答by N Jay

do not use == to compare strings since strings are not primitive data types instead use user.equals("admin")

不要使用 == 来比较字符串,因为字符串不是原始数据类型,而是使用 user.equals("admin")

回答by Shoeb Siddique

You can user equalsIgnoreCase.

您可以使用 equalsIgnoreCase.

This method compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case.

此方法将此 String 与另一个 String 进行比较,忽略大小写考虑。如果两个字符串的长度相同,则认为它们是相等的忽略大小写,并且两个字符串中对应的字符是相等的忽略大小写。

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if (user.equalsIgnoreCase("admin")) {
Toast.makeText(MainActivity.this,"ok",Toast.LENGTH_LONG).show();

            }
            else {
                Toast.makeText(MainActivity.this,"Wrong User Or Pass",Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this,user,Toast.LENGTH_LONG).show();

            }

    });

回答by Koray

When i use this way i solved my problem.

当我使用这种方式时,我解决了我的问题。

  boolean result = String1.equals(String2);
    if (result)
    {
        return  true;
    }
    else
    {
        return  false;
    }