r/programmingbydoing • u/goudarziha • Apr 04 '14
#144 Finding a Value in an Array
So I have been trying multiple ways to do this, but this is the closest I have come. For reasons I am unable to understand, the code only looks at the first item in the array and doesn't go through the loop, like I thought it would.
Scanner s = new Scanner(System.in);
int find = s.nextInt();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == find) {
System.out.print(find + " is in the ArrayList.");
}
}
1
Upvotes
View all comments
Show parent comment
2
u/DoctorBaconite Apr 04 '14
There's a few ways you can do it. You could use a boolean, or an int to keep track of the times it would found.
Either way, when there is a match (line 17) either increment the integer, or set the boolean to true.
Then, after the for loop, if the boolean is still set to false, or the counter == 0, print out
Make sense?