File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Find if an integer is in a given array. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Find if an integer is in a given array." Watch "Find if an integer is in a given array." New topic
Author

Find if an integer is in a given array.

Ibragim Gapuraev
Greenhorn

Joined: Mar 21, 2011
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

Joined: Mar 21, 2011
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
Bartender

Joined: May 31, 2011
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

Joined: Jul 21, 2011
Posts: 171
    
    5

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.


Everything is theoretically impossible, until it is done. ~Robert A. Heinlein
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
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

Joined: Oct 13, 2005
Posts: 39393
    
  28
I was delayed in replying, so didn’t realise that Tina Smith had already given hints about the &&.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Find if an integer is in a given array.