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");
}
}
}
booleanvariable that you set totrueif 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 theforloop .booleantofalseto start with! Then set it totrueif the value is found.