Problem
I want to be able to ask the user to enter a word, then loop through an array that contains words, and search whether that word is in the array.
If the word is not in the array, then it will continue to ask the user for a word until that word is found in the array.
If the word is found in the array, then it will print it out and do something with that word. Loop ends.
Note:
I do not want to use a flag variable. Instead, I want to use only a loop to go through each value in the array and compare it with each new word entered by the user then stop upon the word matching in the array. This method should not use any flag values that stops when changing from false to true, and vice verca.
Program.Java
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userInput;
String array[] = {"Hello", "World"};
System.out.print("Enter word: ");
userInput = input.next();
for(String i : array)
while(!choice.equals(i)) {
System.out.print("Input not found in array. Enter new value: ");
userInput = input.next();
}
System.out.println("Word found in array.");
}
Unintended Output
Instead of stopping when the value in the array is found, it continues to ask for another input, and never terminates.
Example
Enter word: month
Input not found in array. Enter new value: Hello
Input not found in array. Enter new value: World
[...]
Input not found in array. Enter new value:
Intended Output:
Enter word: month
Input not found in array. Enter new value: Hello
Word found in array.
How I want to implement it
To loop through all the values in the array. Compare user input with each value in the array. If the user input matches none of the values in the array, then continue to ask for a new word, until that word matches the value in the array.