Академический Документы
Профессиональный Документы
Культура Документы
Java FAQ
Recent Topics
Register / Login
Author
Ibragim Gapuraev Greenhorn Joined: Mar 21, 2011 Posts: 23
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;
www.coderanch.com/t/556142/java/java/Find-integer-array 1/4
5/11/13
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!
Good... You can additionally have a b r e a k 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: 151
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.
2
www.coderanch.com/t/556142/java/java/Find-integer-array 2/4
5/11/13
I like...
I got it now. If someone hase same problem here is the right one:
Not convinced. Dont write i f( b ). . . t r u e ;e l s e. . . f a l s e ; And you can avoid break by adding the test to the loop continuation condition
view plain c opy to c lipboard print ?
N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped
0 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 6 . 0 7 .
I was delayed in replying, so didnt realise that Tina Smith had already given hints about the &&.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
Similar Threads double precision floating point Problem with Array. max and min in array? For that if use the array? Which is the its main function? Adding Values in arrays.
www.coderanch.com/t/556142/java/java/Find-integer-array 3/4
5/11/13
All times above are in your local time zone & format.T he current ranch time (not your local time) is May 11, 2013 06:40:10 .
www.coderanch.com/t/556142/java/java/Find-integer-array
4/4