Q.Write a java program to search given name into the array, if it is found then display its index otherwise display appropriate message. [15 M]
import java.util.Scanner;
public class SearchName {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Accept number of names
System.out.print("Enter number of names: ");
int n = sc.nextInt();
sc.nextLine();
String[] names = new String[n];
// Accept names
System.out.println("Enter names:");
for(int i = 0; i < n; i++) {
names[i] = sc.nextLine();
}
// Name to search
System.out.print("Enter name to search: ");
String key = sc.nextLine();
boolean found = false;
// Search operation
for(int i = 0; i < n; i++) {
if(names[i].equalsIgnoreCase(key)) {
System.out.println("Name found at index: " + i);
found = true;
break;
}
}
if(!found) {
System.out.println("Name not found in array.");
}
sc.close();
}
}