# Find if an integer is in a given array.

Ibragim Gapuraev
Greenhorn
Posts: 24
Hi everyone. I wrote a simple code to find if an integer is present in an array, but I get wrong answer. If array is a = {1,2,3,4} and int b = 2, it returns false.
Could you point on my mistake, Here is the code:
public class arrayTester {

/**
* @param args the command line arguments
*/
public static boolean isPresented(int anInt, int[] anArray){
boolean result = true;
for (int i = 0;i<anArray.length;i++){

if (anArray[i]==anInt){
result = true;
}
else{
result = false;
}
}

System.out.println(result);

return result;

}
public static void main(String[] args) {
int[] a = {2,3,4,5};
isPresented(2,a);
}
}

Ibragim Gapuraev
Greenhorn
Posts: 24
I got it now. If someone hase same problem here is the right one:
public static boolean isPresented(int anInt){
boolean result = false;
int[] anArray = {2,3,4,5};
for (int i = 0;i<anArray.length;i++){

if (anArray[i]==anInt){
result = true;
}
// no else statement
}

System.out.println(result);

return result;

}
public static void main(String[] args) {

isPresented(4);
}
}

Thanks anyway!

John Jai
Rancher
Posts: 1776
Good... You can additionally have a break statement after you mark the result as true. This way you can prevent unnecessary iterations if any after a match has been spotted.

Tina Smith
Ranch Hand
Posts: 208
9
Another option is to logically 'and' && or 'or' || the result. Unless you have a good reason for initializing a boolean to true, I usually find it's a good idea to use false.

Campbell Ritchie
Sheriff
Posts: 50666
83
Ibragim Gapuraev wrote:I got it now. If someone hase same problem here is the right one:
Not convinced.

Don’t write if (b) ...true; else ...false; And you can avoid break by adding the test to the loop continuation condition

Campbell Ritchie
Sheriff
Posts: 50666
83