If the user searches a number within the array, the system should print out the index that the number is located, if not it would print out search not found. As of now, it works only if there are no duplicate numbers in the array.
I tried removing the break but that would stop the program from printing the second index that also contains the search number.
Any help would be greatly appreciated, thank you!
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
array[0] = 6;
array[1] = 2;
array[2] = 8;
array[3] = 1;
array[4] = 3;
array[5] = 0;
array[6] = 9;
array[7] = 8;
System.out.print("Search for? ");
int searching = Integer.valueOf(scanner.nextLine());
for (int i = 0; i < array.length; i++) {
int input = array[i];
if (searching == input) {
System.out.println(searching + " is at index " + i);
break;
}
else if (searching != array[i] && i == (array.length - 1))
{
System.out.println(searching+" was not found!");
break;
}
}
}
Aucun commentaire:
Enregistrer un commentaire