In: Computer Science
can you fix this problem plz:
I want to return -1 if the element is not found. fix for me just that.
thank you.
public class Search{
public static void main(String[] args) {
Character [] anArray =
{'a','b','c','d'};
Character st = 'a';
iterativeSearch(anArray, st);
//System.out.println(iterativeSearch(anArray,
st));
}
public static <T> boolean iterativeSearch(T[]
anArray, T number) {
boolean found = false;
int index = 0;
while (!found && (index
< anArray.length)) {
if(number.equals(anArray[index])) {
found = true;
System.out.println("Element found at index: " +
index);
}
index++;
}
return found;
}
}
HIGHLIGHTED lines are modified
public class Search{
public static void main(String[] args) {
Character [] anArray = {'a','b','c','d'};
System.out.println(iterativeSearch(anArray, 'd'));
System.out.println(iterativeSearch(anArray, 'e'));
}
public static <T> int iterativeSearch(T[] anArray, T
number) {
boolean found = false;
int index = 0;
while (!found && (index < anArray.length)) {
if(number.equals(anArray[index])) {
found = true;
System.out.println("Element found at index: " + index);
break;
}
index++;
}
if(found == false)
return -1;
return index;
}
}
// Hit the thumbs up if you are fine with the answer. Happy Learning!