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

Thanks DoctorBaconite, I think you might have simplified it for me enough to write it all over again and it works. I am at my work computer and I am not sure why it didn't work in the first place, but thank you for your help!

                    int [] arr = new int[9];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int) (1 + (Math.random() * 50));
			System.out.print(" " + arr[i]);
		}