2

OK so in this program I'm making I have to check if all of the values in the Array are greater than a specific number.

this is what i have so far

public static boolean isGameOver(){
  int check = 0;
  for(int k = 0; k < data.length; k++){
    if (data[k] >= limit)
      check++;
  }
  if (check == data.length)
    return true;
  else 
    return false;
}

the limit variable is the number that all the number in the array have to be grater or qual to.

Can you help me fix this and explain why my way doesn't work?

Robert
  • 23
  • 1
  • 1
  • 4
  • 4
    Do you really need a count, or can you just `return` `false` when you find one value that is below the threshold, and `return` `true` if you get all the way through the loop? – Robert Harvey Nov 01 '13 at 23:33
  • 2
    Which is it: `>` or `>=`? You say "higher than" in the title and "greater than" in the first sentence, but your code says `>=` and another sentence says "grater or qual to [sic]". – rgettman Nov 01 '13 at 23:34
  • 1
    Instead of using your `check` variable, you could put this inside your loop: `if (data[k] < limit) return false;` and return true outside the loop. – Jesan Fafon Nov 01 '13 at 23:35
  • Your algorithm is not optimal, but it should work fine. How doesn't it work? What's your input, what's your expected output, and what's your actual output? Side not: the end of the method could simply be: `return check == data.length;` – JB Nizet Nov 01 '13 at 23:42

2 Answers2

6

Instead of checking if all elements are greater than a specific number just check if one number is less than the specific number and return false if there is one else return true

public static boolean isGameOver(int limit, int[] data){
      for(int k = 0; k < data.length; k++){
        if (data[k] < limit)
          return false;
      }
      return true;
    }
Prateek
  • 1,916
  • 1
  • 12
  • 22
1

Unless you are passing in the value for the limit as well as the array you're checking, the method won't work. Change your header to something like:

public static boolean isGameover(int limit, int[] data)

This should be enough to get your code working (your parameters aren't set up properly). I offer you an alternate solution with less steps involved.

You need to find out if all of the numbers in the array are greater than the limit, so the only condition you need to check is if any of the elements of the array are less than the limit.

for(int i = 0; i < data.length; i++){
    if(data[i] <= limit) // the condition you're checking for is that they're all greater than, so if its less than or equal to, it gets flagged
        return false;
}
return true; // if it goes through the whole array without triggering a false, it has to be true.
Terry Chern
  • 694
  • 1
  • 8
  • 15