Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用三元运算符时的括号_Java - Fatal编程技术网

Java 使用三元运算符时的括号

Java 使用三元运算符时的括号,java,Java,为什么以下两种情况的输出不同?这是一个更大的问题的一部分,我已经调试并缩小到这个问题 public static void main(String[] args) { String test = "hello"; System.out.println(call() + test.charAt(0)=='h'?1:0); } static int call() { return 1; } 输出:0 但是如果我添加

为什么以下两种情况的输出不同?这是一个更大的问题的一部分,我已经调试并缩小到这个问题

public static void main(String[] args) {    

        String test = "hello";
        System.out.println(call() + test.charAt(0)=='h'?1:0);
    }

static int call()
    {
        return 1;
    }
输出:0

但是如果我添加一个偏执,我会得到预期的输出

public static void main(String[] args) {    

        String test = "hello";
        System.out.println(call() + (test.charAt(0)=='h'?1:0));
    }

static int call()
    {
        return 1;
    }
产出:2(如预期)


在初始调用中,call()+test.charAt(0)是否根据“h”进行计算,并相应地分配1和0?这意味着{1+ascii值'h'}==105与ascii值'h'是104进行比较?

这一点不是三元运算符,而是
+
=
之前的事实:

call() + test.charAt(0)=='h'?1:0
在任何读数中是否等于

(call() + test.charAt(0)) == 'h'?1:0
而且,
==
的优先级高于
,因此这等于

((call() + test.charAt(0)) == 'h') ? 1 : 0

实际上没有问题,运算符具有不同的优先顺序

如果你检查他评论中添加的链接,你会发现这个表

如您所见,
加法
+
-
)的优先级高于三元运算符。 这就是为什么:

call() + test.charAt(0)=='h'?1:0
^^^^^^^^^^^^^^^^^^^^^^^
  High precedence      
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       Less precedence
因此,可以使用括号更改优先顺序:

call() + (test.charAt(0)=='h'?1:0)
          ^^^^^^^^^^^^^^^^^^^^^^^
              High precedence      
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       Less precedence

阅读。@AndyTurner,请不要投反对票。我自己几乎已经想出了解决办法。下面的答案得到了这么多的支持票,这意味着人们正在阅读这个问题。我没有否决这个问题。@saltandwater我不认为Andy否决了,但我猜否决票是因为没有表现出任何努力。嗯,这可能是真的,因为这需要一点研究的努力,但这不是一个坏问题,因此我的问题up@FedericoPiazza,谢谢你的回复。但是没有研究工作?我已经能够修复它,并且还建议它是由于105,这确实是正确的答案。这不算是研究工作吗?