Question:
Complete the program so that it asks the user for a number to search in the array. If the array contains the given number, the program tells the index containing the number. If the array doesn't contain the given number, the program will advise that the number wasn't found.
My code:
Scanner scanner = new Scanner(System.in);
int[] array = new int[8];
array[0] = 6;
array[1] = 2;
array[2] = 8;
array[3] = 1;
array[4] = 3;
array[5] = 0;
array[6] = 9;
array[7] = 7;
int searchValueInput = scanner.nextInt();
for (int loopValue = 0; loopValue < array.length; loopValue++) {
if (searchValueInput == array[loopValue]) {
System.out.println(searchValueInput + " is at index " + loopValue + ".");
} else if (searchValueInput > array.length) {
System.out.println(searchValueInput + " was not found.");
}
}
I have modified my code to a simpler logic, because I have complicated it a lot. I have also defined the problem and it is as follows:
How can I check if an element value is inside an array (this part is already done I believe)
How can I check if an element value is not found within the array (this is the part I am missing)
The output result should look similar to the following:
Search for? 3
3 is at index 4.
Search for? 9
9 is at index 6.
Search for? 22
22 was not found.