Java 二元运算符“<=”的错误操作数类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22764883/
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-13 17:45:55  来源:igfitidea点击:

bad operand types for binary operator '<='

javamergesort

提问by user3470113

I can't seem to figure out why i'm getting this error. I've tried putting everything in parenthesis and that helped the problem a little bit. It would be great if I could get some help.

我似乎无法弄清楚为什么我会收到此错误。我试过把所有东西都放在括号里,这对问题有一点帮助。如果我能得到一些帮助,那就太好了。

error: bad operand types for binary operator '<='

错误:二元运算符“<=”的错误操作数类型

Code :

代码 :

public void merge(String[] result, String[] nameA, String[] nameB)
{
    int i1 = 0;   // index into nameA array
    int i2 = 0;   // index into nameB array

    for (int i = 0; i < result.length; i++) 
    {
        if (i2 >= nameB.length || (i1 < nameA.length && nameA[i1] <= nameB[i2])) 
        {
            result[i] = nameA[i1];    // take from nameA
            i1++;
        } 
        else 
        {
            result[i] = nameB[i2];   // take from nameB
            i2++;
        }
    }
}

采纳答案by luksch

In addition to the answers of Luiggi Mendoza and Ivaylo Strandjev I like to point out that if you only want to make sure the strings differ, you can use equals like this:

除了 Luiggi Mendoza 和 Ivaylo Strandjev 的答案之外,我想指出的是,如果您只想确保字符串不同,您可以像这样使用 equals:

if (i2 >= nameB.length || (i1 < nameA.length && !nameA[i1].equals(nameB[i2])))

回答by Luiggi Mendoza

<=and >=operators are for numeric primitive types like intor double. To compare Strings, use compareTomethod.

<=>=运算符用于数字原始类型,例如intor double。要比较Strings,请使用compareTo方法。

nameA[i1].compareTo(nameB[i2]) < 0

If you want to compare Strings by length, then use <=operator on String#lengthinstead:

如果要按String长度比较s,请改用<=运算符 on String#length

nameA[i1].length() <= nameB[i2].length()

回答by Ivaylo Strandjev

In order to compare Strings in Java you need to call the method compareTo. Have a look at the Comparableinterface that Stringimplements.

为了String在 Java 中比较s,您需要调用方法compareTo。查看实现的Comparable接口String