[Solved] Allowing only one negative in arrayList


You have a couple of problems with your code. First, you should stop the loop before i has the value list.size(). (Actually, since the index of the element is not used, you can use an enhanced for loop, which is what I show below.) Second, you need to test for the condition you want, not that each element is <= 0.

You don’t say what kind of values are in the list. If they are integer types (say, Integer), then this should do it:

for (Integer val : list) {
    if (val < -1) {
        throw new IllegalArgumentException();
    }
}

If they are floating point types (say, Float), you need a slightly more complicated test to screen for values like -0.5:

for (Float val : list) {
    if (val < 0 && val != -1) {
        throw new IllegalArgumentException();
    }
}

Also note that if the list can have null entries, you’d need to test for that as well (or document that the method will throw a NullPointerException for such a list).

solved Allowing only one negative in arrayList