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

编写统计布尔数组中true数量的函数遇问题:编译通过但恒返回0

问题修复与解释

你的代码存在两个核心问题,导致无论输入什么布尔数组都返回0:

1. 错误的判断条件

循环里的arr.equals(true)是把整个数组对象和true做比较,永远会返回false。正确的做法是判断当前循环的元素i——直接写i或者i == true即可(因为i本身就是boolean类型)。

2. 循环中错误使用return

循环内的return语句会直接终止整个方法,第一次循环就会返回结果,根本没机会遍历完数组所有元素。你需要的是累加计数,而非提前返回。

修复后的增强for循环版本

public class Challenge {
   public static int countTrue(boolean[] arr) {
      int amountTrue = 0;
      for (boolean i : arr) {
          if (i) {
              amountTrue++;
          }
      } 
      return amountTrue;
   }
}

普通for循环版本(可选)

public class Challenge {
   public static int countTrue(boolean[] arr) {
      int amountTrue = 0;
      for (int j = 0; j < arr.length; j++) {
          if (arr[j]) {
              amountTrue++;
          }
      } 
      return amountTrue;
   }
}

补充说明:amountTrue++是后置自增操作,这里只需要完成计数累加,直接写amountTrue++就足够,不需要在循环里返回它。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:52:07