Scroll
Scroll

Reputation: 178

Array return test

How to return true if all numbers of array go to increase and false if it not?

public static boolean isIncreasing(int[] array){
    boolean result = false;
    int  count = 0;
    for (int i = 0; i < array.length - 1; i++) {
        if(array[i] <= array[i + 1]){
            result = true;
        }else
            result = false;
    }
    return result;
}

When I make test:

isIncreasing([1, 3, 4]) → true
isIncreasing([1, 3, 2]) → false
isIncreasing([1, 1, 4]) → true

but when I try it:

isIncreasing([1,1,2,4,4,2,8,8]) → true

Can someone help me ?

Upvotes: 0

Views: 61

Answers (2)

S-Man
S-Man

Reputation: 23676

4 to 2 gives false.

But that doesn't matter. Because after that 2 to 8 is true again.

Your code just gives out the last comparison.

Better:

public static boolean isIncreasing(int[] array){
    int arraylength = array.length;
    for (int i = 0; i < arraylength - 1; i++) {
        if(array[i] > array[i + 1])
            return false;
    } 
    return true;
}

Upvotes: 1

meJustAndrew
meJustAndrew

Reputation: 6613

It is because you are setting the result to false and then you continue the looping an the result gets overwritten.

Change this:

for (int i = 0; i < array.length - 1; i++) {
    if(array[i] <= array[i + 1]){
        result = true;
    }else
        result = false;
}

To this:

for (int i = 0; i < array.length - 1; i++) {
    if(array[i + 1] <= array[i])
        return false;
}

return true;

This will also reduce the complexity of your code by removing the extra else branch while solving your bug.

Upvotes: 1

Related Questions