1

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");
        }
    }
}
6
  • 3
    Create a boolean variable that you set to true if the number was found (and as soon as the number is found, break; from the loop). Depending on its final value, display what you want after the for loop . Commented Apr 27, 2018 at 7:02
  • To add to Berger statement, create a boolean to false to start with! Then set it to true if the value is found. Commented Apr 27, 2018 at 7:06
  • For the sake of functional style... if (Arrays.stream(test).anyMatch(((Integer)number)::equals)) Commented Apr 27, 2018 at 7:28
  • @Alexander Anikin I tried copying that and it doesn't work for me. What am I forgetting to do? Also, can you explain to me what this line means? Commented Apr 27, 2018 at 7:33
  • @Alexander Anikin I had to import java.util.Arrays, but can you still explain the line Commented Apr 27, 2018 at 7:36

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

"you can't know if an item is not in any position in the array until you have looped through all the items" Not true for a sorted array, which this one happens to be.
@Michael that's not a certitude, since this is not specified in the question this is just a coincidence that this array is sorted.
If I did it the way @NishanthSpShetty did it, do I still need to break the loop?
@AxelH I know it's not certain, but that doesn't mean it is a coincidence. It means it might be a coincidence. It's definitely worth noting that sorted arrays present the opportunity for more efficient search algorithms. This answer to me implies that arrays always require an exhaustive search which is not correct.
@ShinoOG yes, breaking would be a best option, lets say you have list of 1000 int's and you found the value in the beginning, then looping over all the values is a waste.
|
1

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")

8 Comments

So it starts off as false correct? and if the number == val then the variable gets changed to true? Does !found mean if it is not true, the print not in array? @NishanthSpShetty
@ShinoOG !found means not found it's the same as found == false
@NishanthSpShetty but the variable found is now set to true only because number == val, correct?
Yes @ShinoOG, that's what should be said in the explanation of the code ;)
@AxeIH sorry, I just wanted to double check
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.