简体   繁体   English

Java字符串比较无法正常工作

[英]Java string comparison not working as intended



I've done quite a bit of string comparisons in java in the past, but this time it doesn't seem to work. 过去,我已经在Java中做了很多字符串比较,但是这次似乎不起作用。
I'm aware of the fact, that you have to use the .equals() function in order to compare strings in java. 我知道一个事实,您必须使用.equals()函数才能比较Java中的字符串。

In my attempt to figure out what's wrong, I wrote the following code snippet: 为了找出问题所在,我编写了以下代码段:
Log.e("testLogic", String.valueOf(taken.getText().toString().trim().equals('1'))); Log.e("testValue", taken.getText().toString().trim());
producing the following result: 产生以下结果:

E/testLogic﹕ false
E/testValue﹕ 1
E/testLogic﹕ false
E/testValue﹕ 1
E/testLogic﹕ false
E/testValue﹕ 0

This seems rather strange, since the two first 'testLogic' logs should produce true. 这似乎很奇怪,因为前两个“ testLogic”日志应该产生true。
The code is used in a custom list adapter if it means anything. 该代码用于自定义列表适配器(如果有任何含义)。

/Mikkel /米克尔

It is because you are not comparing 2 Strings . 这是因为您没有比较2个Strings You have to put it like this: 您必须这样说:

Log.e("testLogic", String.valueOf(taken.getText().toString().trim().equals("1")));

because .equals() function needs two Strings . 因为.equals()函数需要两个Strings Supposing that s1 and s2 are Strings , you should do: 假设s1s2Strings ,则应该执行以下操作:

s1.equals(s2);

I expect it will be helpful for you! 希望对您有帮助!

The .equals() comes from the Object class. .equals()来自Object类。 Each class inherit it from the Object class. 每个类都从Object类继承它。 String class also inherited it from the Object class and override it like this - String类也从Object类继承它,并像这样覆盖它-

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = count;
            if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                return false;
            }
            return true;
            }
        }
        return false;
  }  

And String has not any overloaded version of equals method for char . 而且String没有charequals方法的任何重载版本。 You can see if String 's .equals() method takes any object but it returns false when it is any type rather than String . 您可以看到String.equals()方法是否接受任何对象,但当它是任何类型而不是String时,它返回false It only returns true if the provided parameter is of type String and is meaningfully equals. 仅当提供的参数为String类型且有意义地等于时,它才返回true So you have to write - 所以你必须写-

Log.e("testLogic",String.valueOf(taken.getText().toString().trim().equals("1"))); 

instead of - 代替 -

Log.e("testLogic", String.valueOf(taken.getText().toString().trim().equals('1')));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM