r/programmingbydoing • • 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

7 comments sorted by

View all comments

Show parent comment

1

u/goudarziha Apr 04 '14

Perhaps, you could also give me some advice for #146 where it asks for simple, yes or no if the value is there. I can't figure out how to get the no part to not repeat throughout the entire look...

https://gist.github.com/anonymous/9979510

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

find + " is not in the array.";

Make sense?

1

u/goudarziha Apr 04 '14

ahh perfect sense!! Thank you so much!