Reputation: 9
So, I'm doing this exercise on edabit for fun, and I got an assertion error. The goal of the exercise is to check and see if there are any numbers in an array that are higher than a given number. Here is my code.
public class ExistsANumberHigher {
public static boolean existsHigher(int[] arr, int n) {
boolean b = false;
for(int num : arr){
if(num > n){
b = true;
}
}
return b;
}
}
When given an array of [4, 3, 3, 3, 2, 2, 2], and a given number of 4, it throws an assertion error. I'm not even sure what an assertion error is. Not looking for improvements to my code other than fixing this error btw. It's a 2-minute challenge. Thank you.
Upvotes: 0
Views: 1244
Reputation: 103463
An AssertionError
is thrown when you write an assertion:
void foo() {
int x = 5;
int y = 6;
assert x > y;
}
asserts are normally not evaluated; the idea is that an assert is not used to verify inputs, solely to state truths, and they serve as documentation primarily. On runs while developing, you let them evaluate.
That you're getting them here is a bit odd; presumably the 'test framework' that checks your existsHigher
impl is written as e.g.:
void checkWork() {
assert ExistsANumberHigher.existsHigher(new int[] {4, 3, 3, 2, 2}, 4);
}
In ohter words, the testcode is broken or the question has a typo - that's my best guess. That they actually want 'higher or equal', so try >=
and see what happens. Or just talk to whomever made this thing, they messed up.
Upvotes: 0