运算符 ^ 未定义参数类型 int,boolean [英] the operator ^ is undefined for argument type(s) int,boolean

查看:139
本文介绍了运算符 ^ 未定义参数类型 int,boolean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决 Hackerrank 问题最大化异或".(https://www.hackerrank.com/challenges/maximizing-xor)>

我已经使用 'if' 语句来检查 i xor j 是否大于 'max',如代码所示.

static int maxXor(int l, int r) {整数最大值=0;for(int i=l;i<r;i++)for(int j=l;jmax)/*错误部分*/最大值=i^j;}返回最大值;}

但是为什么我会收到这个错误?

<块引用>

未定义参数类型 int,boolean' 的运算符 ^

解决方案

你需要在表达式周围加上括号:

if ( (i ^ j) > max )

<小时>

根据Java的运算符优先级表,异或运算符^ 的优先级低于不等运算符 >.

因此你对i ^ j >的原始书面表达max 将被解释为 i ^ (j > max).但在这里,类型不正确:iint,但 (j > max)boolean>.这就是您遇到编译器错误的原因.

<小时>

作为旁注,如果您用 C/C++ 编译此代码,它会编译但运行时会出现奇怪的结果.这是因为在 C/C++ 中,相同的运算符优先级规则适用于这种情况,但是 bool 将转换为 0 或 1 的 int,然后进行 XOR会继续.这将是危险和错误的.Java 编译器阻止您对 intboolean 进行异或,这将是一个荒谬的操作.

I am solving Hackerrank problem 'Maximizing xor'. (https://www.hackerrank.com/challenges/maximizing-xor)

I have used 'if' statement to check if i xor j is greater than 'max' as shown in code.

static int maxXor(int l, int r) {
    int max=0;
    for(int i=l;i<r;i++)
        for(int j=l;j<r;j++)
        {
            if(i^j>max)/*error part*/
            max=i^j;
        }
    return max;
}

But why am I getting this error?

the operator ^ is undefined for argument type(s) int,boolean'

解决方案

You need to put parentheses around the expression:

if ( (i ^ j) > max )


According to Java's operator precedence table, the XOR operator ^ has lower precedence than the inequality operator >.

Therefore your original written expression of i ^ j > max would be interpreted as i ^ (j > max). But here, the types are incorrect: i is an int, but (j > max) is a boolean. That's why you got that compiler error.


As a side note, if you compiled this code in C/C++, it would have compiled but it would run with bizarre results. This is because in C/C++, the same operator precedence rules apply in this case, but the bool would be converted to an int of 0 or 1, and then the XOR would proceed. This would have been dangerous and wrong. The Java compiler stopped you from XORing an int with a boolean, which would be a nonsensical operation.

这篇关于运算符 ^ 未定义参数类型 int,boolean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆