Home > OS >  Using a loop to check each element in an array and return true or false
Using a loop to check each element in an array and return true or false

Time:09-26

I'm trying to write a loop that checks each element in an array that contains test scores. If the test score meets the threshold then it should return true or false in that location. Here's the code so far. I felt I was on the right track and understand how it should be done but don't know enough Java to do so.

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;

  }
}

CodePudding user response:

Simply assign the value of scores[i] > threshold to your bool array:

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

for (int i = 0; i < highScores.length; i  )
    highScores[i] = scores[i] > threshold;
  •  Tags:  
  • java
  • Related