Skip to content
Advertisement

Using a FOR-EACH loop, how would you keep count of the number of scores over 85?

There is another test case not shown here with about 6 different test scores. How do I use a FOR-EACh loop to keep count of the number of scores over 85?

public class BetterLoop {
  /**
   * Accept an applicant if they have at least 4 grades above 85. Their non-CS
   * GPA counts as a grade in this case.
   * 
   * @param scores The applicant's list of scores
   * @return true if the applicant meets the requirements
   */
  public static boolean atLeastFourOver85(int[] scores) {
    /*
     * Use a FOR-EACH loop. How would you keep count of the number of scores over 85?
     */
    int total = 0;
    for(int score: scores){
      if (score < 85);
      total += 1;
    }

      

    return false;
  }

Advertisement

Answer

I would write something like this:

public static boolean atLeastFourOver85(int[] scores) {
    /*
     * Use a FOR-EACH loop. How would you keep count of the number of scores over 85?
     */

    int found = 0;
    for(int score : scores) {
        if (score > 85)
            found++;
    }
    return found >= 4;
}

And here is the unit test:

class BetterLoopTest {

@Test
public void testLoop(){
    assertFalse(BetterLoop.atLeastFourOver85(new int[]{1,2,3}));
    assertFalse(BetterLoop.atLeastFourOver85(new int[]{1,2,3,86,86,86,34}));

    assertTrue(BetterLoop.atLeastFourOver85(new int[]{1,2,3,86,86,86,34,86,45}));
}

}

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement