Count the number of 5.0 from the start of a List-Linked

1

I try to solve a function that returns the position of the first '5.0' from the beginning in a LinkedList. I must return a negative number if the list is empty or if the first item on the list is not a '5.0'.

The function passes the tests when it finds the first '5.0' but fails when the first item on the list is not a '5.0'. I would like to know if there is an error in the logic of my function or if it is the way in which the tests are written? Any clue that goes wrong is a big help, thanks!

The function returns the position of the first '5.0' from the beginning:

    public int positionOfFirstFiveFromBeginning(){
    int result = 0;
    if(first == null){
        return -1;
    }
    Node x = first;
    while(x != null){
        if(x.item == 5.0){
            return result;
        }
        result++;
        x = x.next;
    }
    return result;
}
  

Failed [11] .positionOfFirstFiveFromBeginning (): Expecting [-1]   Current [1]

     

Failed [11 21 31 41] .positionOfFirstFiveFromBeginning (): Expecting   [-1] Current [4]

     

Finished tests

Function fails all tests when I modify it to count the item that is not a '5.0':

    public int positionOfFirstFiveFromBeginning(){
    int result = 0;
    if(first == null || first.item != 5.0){
        return -1;
    }
        Node x = first;
        while (x != null) {
            if (x.item == 5.0) {
                return result;
            }
            result++;
            x = x.next;
        }
    return result;
}
  

Failed [11 5 21 31 41] .positionOfFirstFiveFromBeginning (): Expecting   [1] Current [-1]

     

Failed [11 21 5 31 41] .positionOfFirstFiveFromBeginning (): Expecting   [2] Current [-1]

     

Failed [11 21 31 5 41] .positionOfFirstFiveFromBeginning (): Expecting   [3] Current [-1]

     

Failed [11 21 31 41 5] .positionOfFirstFiveFromBeginning (): Expecting   [4] Current [-1]

     

Failed [0 1 2 5 5 5 5 5 8 9] .positionOfFirstFiveFromBeginning ():   Expecting [3] Current [-1]

     

Finished tests

    
asked by J.user94 17.07.2017 в 18:21
source

1 answer

1

I would think that it would be best to leave it as the first one modifying the last Return , that is:

public int positionOfFirstFiveFromBeginning(){
int result = 0;
if(first == null){
    return -1;
}
Node x = first;
while(x != null){
    if(x.item == 5.0){
        return result;
    }
    result++;
    x = x.next;
}
return -1; //en vez de "result" 
}

I hope it helps!

    
answered by 17.07.2017 / 18:45
source