Cyber Allien - 2 years ago 53
Java Question

# Add the searching value from parameter in this fonction

This question follows my brevious one on how to Return value of smallest index of repeated number in array.

In this function given to me by @Andreas:

``````private static void printFirstIndexOfRepeated(int[] values) {
Integer firstIndex = null;
Map<Integer, Integer> mapValueToIndex = new HashMap<>();
for (int i = 0; i < values.length; i++) {
Integer prevIndex = mapValueToIndex.put(values[i], i); // put() returns old value, or null
if (prevIndex != null && (firstIndex == null || prevIndex < firstIndex))
firstIndex = prevIndex;
}
if (firstIndex != null)
System.out.println("First index of repeated: " + firstIndex);
else
System.out.println("No repeat found");
}
``````

Function test:

``````int [] array = {10,5, 4, 3, 5, 6};
printFirstIndexOfRepeated(array);
``````

Output

`First index of repeated: 1 // it looks for 5 and return the value of smallest index of repeated 5 in array.`

Due to my lack of programming knowledge with Map, I'm new and I know only Array. I need some help to transform this function and add another parameter like (int number) to decide witch number I'm looking for and not automatically

The desired one :
`printFirstIndexOfRepeated(int[] values, int number)`

So because you basically just want the index of the first occurrence of a given number inside an array, you don't need the `Map` at all. Instead you can just use a simple for loop:

``````private static int printFirstIndexOfRepeated(int[] values,int number) {
for(int i = 0; i < values.length; i++){
if(values[i] == number){
//System.out.println("The first index of " + number + " is " + i);
return i;
}
}
return -1;
//System.out.println(number + " is not a member of the array.");
}
``````

This function returns the first index of a given number or `-1` if the number was not found. You can uncomment the `print` lines to also get an output if you like (or just delete them).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download