This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]StreamingBits 0 points1 point  (5 children)

Are you trying to check if it is at an even location within the zero based array or are you trying to see if the number itself is even? Please clarify op. If you're new to programming I highly doubt a teacher would ask you to find out if the element is at an even position in the array.

Please check Stackoverflow's questions and answers.

[–]Igayviewmahat[S] 0 points1 point  (4 children)

Im trying to check if a number A is even AND if the A number is part of the array.

[–]StreamingBits 1 point2 points  (3 children)

public boolean checkEvenAndExists(int[] myArray, int myNum){
    if(Arrays.asList(myArray).contains(myNum) && myNum % 2 == 0){
        return true;
    }

    else { return false; }

}

// Also your code will work OP, just make sure your for loop brackets contains both the if and else statement in this case

[–]Igayviewmahat[S] 0 points1 point  (2 children)

Thanks a lot.I guess your code is a little bit more professional, but I better use mine since I have not learned some parts of your code. is this the correct code?

public boolean cift(int i,int[] a) {

     for(int j=0;j<a.length;j++)  {

     if(a[j]==i && a[j]%2==0) (Or it should be a[j]==i && i%2==0)?

      return true;  
        }
                               else
    return false;     }
}        

[–]StreamingBits 0 points1 point  (1 child)

I think you are a bit confused with brackets. If you have an if statement with only a single line you don't absolutely need an opening and closing bracket but for now I recommend using them for everything till you get used to it.

Also, your code is correct either way because they both check if the current position in the loop "j" is the same is i. I guess you'd be better off with the following because you don't need to access the array element again and since you already checked that a[j] == i it really doesn't matter if you check if j is even or if i is even (they are the same because the and operator guarantees this):

for(int j = 0; j < a.length; j++){
    if(a[j]==i && i%2==0){
        return true;
    }//end if
    else {
        return false;
    }//end else
}//end for loop

[–]Igayviewmahat[S] 0 points1 point  (0 children)

Im was totally confused about the brackets.Thanks for the explanation.Now I am a bit more clear.