public class PhoneBookEntry { private String name; private String phoneNumber; /** * The PhoneBookEntry is a constructor that takes two strings as inputs * @param n for name field * @param pn for phoneNumber field */ public PhoneBookEntry(String n, String pn) { name = n; phoneNumber = pn; } public void setName(String n) { name = n; } public void setPhone(String pn) { phoneNumber = pn; } public String getName() { return name; } public String getPhoneNumber() { return phoneNumber; } }
import java.util.Scanner; import java.util.ArrayList; public class PhoneBookDemo { public static void main(String args[]) { // Constant for the numer of entries. final int NUM_ENTRIES = 5; // Create an ArrayList, named list, to hold PhoneBookEntry objects. ArrayList <PhoneBookEntry> list = new ArrayList<PhoneBookEntry>(); System.out.println("I'm going to ask you to enter " + NUM_ENTRIES + " names and phone numbers."); System.out.println(); // Store PhoneBookEntry objects in the ArrayList. for (int i = 0; i < NUM_ENTRIES; i++) { list.add( getEntry() ); System.out.println(); } System.out.println("Here's the data you entered:"); // Display the data stored in the ArrayList. for (int i = 0; i < list.size(); i++) { displayEntry(list.get(i)); } } /** The getEntry method creates a PhoneBookEntry object populated with data entered by the user. @return A reference to the object. */ public static PhoneBookEntry getEntry() { //Creates new scanner objects Scanner keyboard = new Scanner(System.in); //Prompts user to enter name and number System.out.println("Enter name: "); String input = keyboard.nextLine(); System.out.println("Enter phone number associated: "); String input2 = keyboard.nextLine(); //Apply user inputs in a new PhoneBookEntry object PhoneBookEntry entry = new PhoneBookEntry(input,input2); //Returns the reference object return entry; } /** The displayEntry method displays the data stored in a PhoneBookEntry object. @param entry The entry to display. */ public static void displayEntry(PhoneBookEntry entry) { System.out.println(entry); } }
- Basically the PhoneBookEntry class is the method class with field "name" and "phone#".
- Main class is the demo, which creates PhoneBookEntry objects and stores it in an arraylist
I am required to use ArrayList by the assignment and also use the methods in the demo class (they are required)
I am little confusing in passing ArrayList in methods.
I am not sure how to display entries in displayEntry() in main class.
ERROR DISPLAYED:
Here's the data you entered:
PhoneBookEntry@34b23d12
PhoneBookEntry@21c783c5
PhoneBookEntry@319c0bd6
PhoneBookEntry@7bcd280b
PhoneBookEntry@5a0029ac