Java三元运算符优先级?给定不同的输出 [英] Java ternary operator precedence ? Different outputs given

查看:52
本文介绍了Java三元运算符优先级?给定不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码生成此输出( -1之后没有空格)==> "1 3 -14 -15 -1 >

  int [] arr = {1,3,Integer.MAX_VALUE,4,Integer.MAX_VALUE,5,Integer.MAX_VALUE};为(int dist:arr){System.out.print((dist == Integer.MAX_VALUE)?-1:dist +");} 

但是,如果我分别评估三元表达式(如下所示),它将给出不同的输出(我期望的结果)==> "1 3 -1 4 -1 5 -1"

  int [] arr = {1,3,Integer.MAX_VALUE,4,Integer.MAX_VALUE,5,Integer.MAX_VALUE};为(int dist:arr){int finalDist =(dist == Integer.MAX_VALUE)吗?-1:dist;System.out.print(finalDist +");} 

第一个代码段出了什么问题?

解决方案

此处

 (dist == Integer.MAX_VALUE)吗?-1:dist +" 

仅当条件为 false 时,才会添加空格.您应该始终使用括号来添加" ,如下所示.

 (((dist == Integer.MAX_VALUE)?-1:dist)+" 

三元运算符只有运算符优先于赋值运算符.(请参见下文)


I have the below code producing this output (no space after -1) ==> "1 3 -14 -15 -1"

int [] arr = {1, 3, Integer.MAX_VALUE, 4, Integer.MAX_VALUE, 5, Integer.MAX_VALUE};
for (int dist : arr) {
    System.out.print((dist == Integer.MAX_VALUE) ? -1 : dist + " ");
}

But if I evaluate the ternary expression separately (as shown below), it gives a different output (what I expected) ==> "1 3 -1 4 -1 5 -1"

int [] arr = {1, 3, Integer.MAX_VALUE, 4, Integer.MAX_VALUE, 5, Integer.MAX_VALUE}; 
for (int dist : arr) {
    int finalDist = (dist == Integer.MAX_VALUE) ? -1 : dist;
    System.out.print(finalDist + " ");          
}

What is going wrong with the first code snippet?

解决方案

Here

(dist == Integer.MAX_VALUE) ? -1 : dist + " "

The space will be added only if the condition is false. You should use parantheses to add " " at all times like below.

((dist == Integer.MAX_VALUE) ? -1 : dist) + " "

The ternary operator has only operator precedence over the assignment operators. (See below)


Oracle Site about Operator Precedence

The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence.

这篇关于Java三元运算符优先级?给定不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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