如何使用OR运算符

时间:2013-08-30 23:16:43

标签: java

我正在处理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 个答案:

答案 0 :(得分:5)

请勿将int值与赋值运算符=进行比较。使用==进行比较,从而产生所需的boolean。变化

if((counter = 0) ||

if((counter == 0) || // And the others after it also.

答案 1 :(得分:0)

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

答案 2 :(得分:0)

不应该是

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

注意双==

答案 3 :(得分:0)

虽然其他答案直接适用,但这对于% (or modulus) operator来说是一个合适的案例,因为它可以非常简单地代码:

// 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(键入为{ {1}}),这在Java中没有意义 - 在这种情况下,提供给运算符的操作数(值)中的一个或两者都是无效的,因为Java在键入时只接受int || int ||

相反,boolean || boolean求值为布尔值,counter == 0求值为布尔值,因此Java对表达式的类型counter == 10感到满意。