I need to see when a given variable value in an array is first occurred and once occurred change that variable to the number when it first occurs, and if it does not occur than change the value to -1. For example 32 appears first in the array so it should print 1 but 100 never appears in the array so it should print -1 but how do I make a second if statement in my loop so that the variable will be -1 but it test the original value to find it appears. Sorry if I did not explain it well enough.
here is the code for the loop and the first if statement
public static int occurrence(int[] a) {
Scanner scnr = new Scanner(System.in);
int occurrence = scnr.nextInt();
for (int i = 0; i < a.length; i++)
if (a[i] == occurrence)
occurrence = i + 1;
return occurrence;
Aucun commentaire:
Enregistrer un commentaire