CJ_Slip15

Slip No.15

A) Write a java program to search given name into the array, if it is found then display its index otherwise display appropriate message.

1. Open Notepad.

2. Type the following code:

    import java.util.Scanner;

    public class NameSearch {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Sample array of names
    String[] names = {"Raj", "Amit", "Sneha", "Priya", "Ankit"};

    System.out.print("Enter the name to search: ");
    String searchName = scanner.nextLine();

    boolean found = false;

    // Loop to search the name
    for (int i = 0; i < names.length; i++) {
    if (names[i].equalsIgnoreCase(searchName)) {
    System.out.println(searchName + " found at index " + i);
    found = true;
    break;
    }
    }

    if (!found) {
    System.out.println(searchName + " not found in the array.");
    }

    scanner.close();
    }
    }
3. Save the file with the name NameSearch.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Open the Command Prompt.

5. Compile the Java program by typing:
javac NameSearch.java

6. Run the compiled Java program by typing:
java NameSearch

No comments:

Post a Comment