Write a class PhoneEntry which had two data members, name and phoneNumber, to si
ID: 673045 • Letter: W
Question
Write a class PhoneEntry which had two data members, name and phoneNumber, to simulate the entry for a phone book. It has a constructor that takes two parameters to initialize the two data members, and some necessary accessor methods.
Then write a class PhoneBook which has contact, an array of 5 PhoneEntry, as a data member. It has:
A constructor to initialize the contact.
A method search which takes a parameter targetName and it returns the PhoneEntry of the phone with targetName.
Write a program to test your PhoneBook. Prompt user to enter a name, display the name and phone number of the person, or if no entry found, display the corresponding message.
Explanation / Answer
import java.io.*;
class PhoneEntry
{
String name;
int phoneNumber;
public PhoneEntry(String n, int p)
{
this.name = n;
this.phoneNumber=p;
}
}
class PhoneBook
{
PhoneEntry[] contact=new PhoneEntry[5];
public PhoneBook()
{
contact[0]=new PhoneEntry("aaa",12345);
contact[1]=new PhoneEntry("bbb",12346);
contact[2]=new PhoneEntry("ccc",12347);
contact[3]=new PhoneEntry("ddd",12348);
contact[4]=new PhoneEntry("eee",12349);
}
void search(String targetName)
{
int a,c=0;
for(int i=0;i<5;i++)
{
if(targetName.equals(contact[i].name))
{
c=1;
System.out.println(contact[i].name);
System.out.println(contact[i].phoneNumber);
}
}
if(c==0)
{
System.out.println("No entry found");
}
}
}
class phone_b_search
{
public static void main(String args[]) throws IOException
{
PhoneBook b= new PhoneBook();
System.out.println("Enter Name to search");
DataInputStream o = new DataInputStream(System.in);
String s= o.readLine();
b.search(s);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.