You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用多个三元运算符计算整数结果异常,始终返回1,求问题原因

问题分析与解决:三元运算符累加结果异常

你的代码出现问题的核心原因是运算符优先级错误。在Java中,加法运算符+的优先级高于三元条件运算符?:,导致你的代码被编译器错误解析,完全偏离了原本的累加逻辑。

错误解析后的实际逻辑

编译器会把你的代码拆解成如下结构:

int finalValue = (
      tempArray[1] == 1 ? 1 : (0 + tempArray[5] == 1 ? 1 : (0 + tempArray[8] == 1 ? 1 : (0 + tempArray[10] == 1 ? 1 : (0 + tempArray[12] == 1 ? 1 : (0 + tempArray[15] == 1 ? 1 : 0))))));

这意味着:

  • 首先判断tempArray[1]是否等于1,如果是直接返回1,不会执行后面的任何判断
  • 如果第一个条件不满足,才会计算0 + tempArray[5]的值,再判断是否等于1,以此类推
    这种逻辑自然会导致finalValue始终返回1(只要第一个元素满足条件),或者得到完全不符合预期的结果。

修复方案

方案1:给每个三元表达式加括号

通过括号强制让每个三元运算先执行,再进行累加:

int finalValue = (
      (tempArray[1] == 1 ? 1 : 0) +
      (tempArray[5] == 1 ? 1 : 0) +
      (tempArray[8] == 1 ? 1 : 0) +
      (tempArray[10] == 1 ? 1 : 0) +
      (tempArray[12] == 1 ? 1 : 0) +
      (tempArray[15] == 1 ? 1 : 0)
);

方案2:使用累加变量(可读性更高)

把累加操作拆分,代码更直观,也不容易出错:

int finalValue = 0;
finalValue += tempArray[1] == 1 ? 1 : 0;
finalValue += tempArray[5] == 1 ? 1 : 0;
finalValue += tempArray[8] == 1 ? 1 : 0;
finalValue += tempArray[10] == 1 ? 1 : 0;
finalValue += tempArray[12] == 1 ? 1 : 0;
finalValue += tempArray[15] == 1 ? 1 : 0;

方案3:循环遍历索引(最易维护)

如果后续需要调整检查的索引,这种方式修改起来最方便:

int[] targetIndices = {1, 5, 8, 10, 12, 15};
int finalValue = 0;
for (int idx : targetIndices) {
    if (tempArray[idx] == 1) {
        finalValue++;
    }
}

内容的提问来源于stack exchange,提问作者asajadi84

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:05:17