-6

我正在使用 if 语句:

if(test == 1 || test == 2){
    do something
}

我在 Java 中工作,不知何故,这段代码会产生“错误操作数类型”的错误。我知道它是 OR (||) 但我不知道如何解决它。代码:

public static int[] map = 
//1  2  3  4  5  6  7  8  9 10
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //0
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //1
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //2
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //3
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //4
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //5
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //6
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //7
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //8
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //9
};
public static int mapRow, mapCol;
public static int mapRef = (mapRow + (mapCol * 10)) - 1;

String grass = "[ ] ";
String water = "{} ";

private int counter = 0;

void mapCreate(){
    while(counter != 99){
        if((counter = 0) || (counter = 10) || (counter = 20) || (counter = 30) || (counter = 40) || (counter = 50) 
                                           || (counter = 60) || (counter = 70) || (counter = 80) || (counter = 90) || (counter = 100)){
            if(map[counter] == 1){
                System.out.println(grass);
            } else if(map[counter] == 2){
                System.out.println(water);
            }
        } else {
            if(map[counter] == 1){
                System.out.print(grass);
            } else if(map[counter] == 2){
                System.out.print(water);
            }
        }
        counter++;
    }
}

错误:

mapcreater.java:27: error: bad operand types for binary operator '||'
        if((counter = 0) || (counter = 10) || (counter = 20) || (counter = 30) ||         (counter = 40) || (counter = 50)
4

4 回答 4

5

不要将int值与=赋值运算符比较。用于==比较,结果需要boolean. 改变

if((counter = 0) ||

if((counter == 0) || // And the others after it also.
于 2013-08-30T23:24:18.673 回答
0

检查test变量的类型。您可能正在尝试将非数字类型与文字数字进行比较。

于 2013-08-30T23:21:47.083 回答
0

难道不应该

if((counter == 0) || (counter == 10) || (counter == 20) || (counter == 30) 

注意双==

于 2013-08-30T23:25:26.677 回答
0

%虽然其他答案直接适用,但这对于(或模数)运算符来说是一个合适的情况,因为它可以极大地简化代码:

// use `==` (equality), not `=` (assignment)
if (counter % 10 == 0) {  
  // when counter is 0, 10, 20, etc ..
  ..
}

现在,类型错误是“错误的操作数类型”,因为用作表达式的赋值计算为它们被分配的值:

因此,counter = 0计算结果为 0(类型化int),counter = 10计算结果为 10(类型化int),这导致0 || 10(类型化为int || int),这在 Java 中没有意义——在这种情况下,提供给运算符无效,因为 Java 仅||在输入为. 时才接受boolean || boolean

相反,counter == 0计算为布尔值并counter == 10计算为布尔值,因此 Java 对表达式的类型感到满意,即boolean || boolean.

于 2013-08-30T23:27:58.707 回答