KnowledgeBoat Logo
|

Computer Applications

Define a class to accept 5 names in one array and their respective telephone numbers into a second array. Search for a name input by the user in the list. If found, display "search successful" and print the name along with the telephone number, otherwise display "Search unsuccessful: Name not enlisted".

Java

Java Arrays

20 Likes

Answer

import java.util.Scanner;

public class KboatTelephoneNos
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int n = 5;
        String names[] = new String[n];
        String numbers[] = new String[n];
        
        for (int i = 0;  i < n; i++) {
            System.out.print("Enter Name: ");
            names[i] = in.nextLine();
            System.out.print("Enter Telephone number : ");
            numbers[i] = in.nextLine();
        }
        
        System.out.print("Enter name to be searched : ");
        String name = in.nextLine();
        
        int idx;
        for (idx = 0;  idx < n; idx++) {
            if (name.compareToIgnoreCase(names[idx]) == 0) {
                break;
            }
        }
        
        if (idx < n) {
            System.out.println("Search Successful");
            System.out.println("Name : " + names[idx]);
            System.out.println("Telephone Number : " + numbers[idx]);
        }
        else {
            System.out.println("Search Unsuccessful : Name not enlisted");
        }
    }
}

Output

BlueJ output of Define a class to accept 5 names in one array and their respective telephone numbers into a second array. Search for a name input by the user in the list. If found, display "search successful" and print the name along with the telephone number, otherwise display "Search unsuccessful: Name not enlisted".BlueJ output of Define a class to accept 5 names in one array and their respective telephone numbers into a second array. Search for a name input by the user in the list. If found, display "search successful" and print the name along with the telephone number, otherwise display "Search unsuccessful: Name not enlisted".

Answered By

10 Likes


Related Questions