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

Java代码中else if(Weight>5<10)布尔错误修复求助

问题修复方案

你的问题出在Java不支持数学表达式里的连续范围写法,Weight > 5 < 10这种语法在Java里会被错误解析成(Weight > 5) < 10——把布尔值(true/false)和整数10比较,这在Java里是不允许的,所以触发了布尔错误。

修复后的代码(两种可选写法)

写法1:明确的逻辑与判断

if (Weight < 6) {
    Price = 5;
    System.out.println("The price of cleaning will be" + Price);
} else if (Weight > 5 && Weight < 10) { // 用&&连接两个独立条件
    Price = 8;
    System.out.println("The price of cleaning will be" + Price);
} else if (Weight >= 10) {
    Price = 12;
    System.out.println("The price of cleaning will be" + Price);
}

写法2:简化判断(更高效)

因为第一个if已经处理了Weight <6的情况,进入else if时必然满足Weight >=6,所以可以直接写:

if (Weight < 6) {
    Price = 5;
    System.out.println("The price of cleaning will be" + Price);
} else if (Weight < 10) { // 无需再判断>5,前面的条件已经排除了小于6的情况
    Price = 8;
    System.out.println("The price of cleaning will be" + Price);
} else { // 剩下的必然是Weight >=10,无需额外判断
    Price = 12;
    System.out.println("The price of cleaning will be" + Price);
}

说明

  • Java中判断范围必须用逻辑运算符(&&表示“且”,||表示“或”)连接多个独立条件。
  • 第二种写法利用了条件判断的顺序性,减少了一次比较,代码更简洁高效。

内容的提问来源于stack exchange,提问作者ńmȋć

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:25:26