ShinoOG
ShinoOG

Reputation: 17

Arrays and For Loop (JAVA)

This is probably a simple question, but how do I display "not in array" 1 time if the value I declared before isn't in the array? I got it to display "in array" by using an enhanced for loop to loop through the array. I noticed that if I added an else after the if, it would display "not in array" 4 times.

I'm still new to programming and have read the chapter, but I get so confused when it comes to arrays and for loops. Any help would be appreciated.

public static void main(String[] args) {

    int[] test = {1, 2, 3, 4, 5};  // Creating an array
    int number = 5;                 // My test number

    // Enhanced for loop
    for (int val: test) {
        if (number == val) {
            System.out.println(number + " in array");
        }
    }
}

Upvotes: 1

Views: 101

Answers (2)

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

The fundamental issue is that you can't know if an item is not in any position in an unsorted array until you have looped through all the items. If you check each item individually, you can't know if the next item might match.

Use a boolean variable to keep track of whether you've seen the item, and only print the result after the loop, once you've gone through all of them. Also check out break, you can use it to exit the loop if you don't need it to go all the way through.

After you've figured that out, a good next exercise is to extract the loop into a separate method and use return instead of break. Then you won't even need the boolean variable anymore.

Upvotes: 2

NishanthSpShetty
NishanthSpShetty

Reputation: 659

use the flags,

boolean found = false; 
for (int val: test) {
    if (number == val) {
        //System.out.println(number + " in array");
       //set the flag if found 
       found=true;
       //stop once you found what you looking for
       break;
    }
}
//check if the flag is set
if(!found)
    System.out.println(number + " is not in array")

Upvotes: 1

Related Questions