Im trying to list the items in an array list from another class.
I have 3 classes in total
Tell - The main program
Item - The class that creates individual telephone directory items
Directory - A directory object which stores all the items.
What I'm trying to do is list all the items within the array list created in "directory" and im doing it like this....
TELL
if (Directory.entries.size>0)
{
for (int i=0; i<Directory.entries.size(); i++) // Check size of array
{
Directory.entries.get(i).showRecord();
}
}
DIRECTORY
public void printItem()
{
//I HAVE NO IDEA WHAT GOES HERE
}
ENTRY
public class Entry
{
String name;
String telNo;
public Entry(String aName, String aTelNo )
{
setNumber(aTelNo);
setName(aName);
}
// Add methods here
private void setNumber(String aTelNo)
{
telNo = aTelNo;
}
public String getNumber()
{
return telNo;
}
private void setName(String aName)
{
name = aName;
}
public String getName()
{
return name;
}
public String toString()
{
return name + "." + telNo;
}
}
However I havnt got the foggiest what needs to go in the printItem() Method to allow me to print the individual items in the directory.
Could someone point me in the right direction? This is the first time I have ever really used array lists accross multiple classes and I'm very confused.
Since you have overrided the toString
in your Entry
class, so what all you need to do is iterate over your List and print each item. It will automatically invoke the toString of your Entry class and print the returned value: -
Put this code in your print
method, which is in Directory
class.
public static void print() {
for (Entry entry: Directory.entries) {
System.out.println(entry);
}
}
entries
is the static
list you have in your Directory
class.
And from your Tell
class, just invoke your print
method:-
Directory.print();
Right now you don't have a call to printItem()
; I am assuming your call to .showRecord()
is either going to replace printItem()
or be removed because they are trying to accomplish the same thing.
Assuming that you remove .showRecord()
and just use printItem()
instead, and that you are using some type of collection with data member named entries
inside the Directory
class:
public void printItem() {
for (Entry entry : this.entries) {
System.out.println(entry);
}
}
is all you need since you already overrode the toString()
function inside your Entry
class. This iterates through each entry in the directory for you and prints them on at a time on separate lines.
You can use TreeMap<String, String>
to hold the telephone directory list of items. TreeMap will ensure that your keys are sorted in Natural order (by person name) and that there are no duplicate names in the directory (every persons name is unique ). To print an entry would be a simple String treeMap.get(key);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.