首页 > 解决方案 > 使用循环检查数组中的每个元素并返回 true 或 false

问题描述

我正在尝试编写一个循环来检查包含测试分数的数组中的每个元素。如果测试分数达到阈值,那么它应该在该位置返回真或假。这是到目前为止的代码。我觉得我走在正确的轨道上,并且了解应该如何完成,但对 Java 的了解还不够多。

public class SimpleArray {

  /**
   * Write a function that takes in an applicant's numerical scores and returns
   * Boolean values to tell us if they are above a certain threshold.
   * 
   * For example, if the applicant's scores are [80, 85, 89, 92, 76, 81], and the
   * threshold value is 85, return [false, false, true, true, false, false].
   * 
   * @param scores    The applicant's array of scores
   * @param threshold The threshold value
   * @return An array of boolean values: true if the score is higher than
   *         threshold, false otherwise
   */
  public static boolean[] applicantAcceptable(int[] scores, int threshold) {
  
    boolean[] highScores = new boolean[scores.length];

    /*
     * TO DO: The output array, highScores, should hold as its elements the
     * appropriate boolean (true or false) value.
     *
     * Write a loop to compute the acceptability of the scores based on the
     * threshold and place the result into the output array.
     */
    for (int i = 0; i < highScores.length; i++){
      if (highScores[i] <= threshold[i]);


      return highScores;

  }
}

标签: java

解决方案


只需将值分配scores[i] > threshold给您的布尔数组:

boolean[] highScores = new boolean[scores.length];

for (int i = 0; i < highScores.length; i++)
    highScores[i] = scores[i] > threshold;

推荐阅读