PhoneBook类没有正确地保存Entry对象

时间:2014-09-20 01:48:05

标签: java oop

我有一个程序从一个文件中读取,该文件包含这种格式的名字,姓氏和电话号码:John Doe 123-456-7890

程序将这些作为字符串读取并将它们输入到Entry类中,然后将Entry对象添加到PhoneBook中。还有其他打印功能。现在,当我打印它时,它只是打印最后一个条目56次(txt文件中有56个“条目”)。无论出于何种原因,条目正确地传递给Entry类,因为我可以正确地打印它们但是当我将它们添加到PhoneBook并尝试打印它时只打印最后一个条目。任何帮助将不胜感激我如何搞砸了。谢谢!

main`

import java.util.Scanner;
import java.io.*;

public class main{

public static void main(String[] args) throws FileNotFoundException{
    String firstName, lastName, fullName, phoneNumber;
    Entry entry = new Entry();
    PhoneBook phonebook = new PhoneBook();

    File myFile = new File("C:\\Users\\Gregory\\Desktop\\Names_Numbers.txt");
    Scanner infile = new Scanner(myFile);

    //check if file exists
    if (!myFile.exists()){
        System.out.println("File not able to be found");
        System.exit(0);
    }

    while (infile.hasNext()){
        firstName=infile.next();
        lastName=infile.next();
        fullName=firstName+ " " + lastName;
        phoneNumber=infile.next();
        entry.setName(fullName);
        entry.setPhoneNumber(phoneNumber);
        phonebook.add(entry); 
    }

    phonebook.print();
    infile.close();


}
}`

入门课程

public class Entry {
private String name;
private String phoneNumber;

public Entry() {
    name = " ";
    phoneNumber = " ";
}
public Entry(String n, String pN) {
    name=n;
    phoneNumber=pN;
}
public void setName(String fullName) {
    name=fullName;
}
public void setPhoneNumber(String pN){
    phoneNumber=pN;
}
public String getName() {
    return name;
}
public String getPhoneNumber(){
    return phoneNumber;
}
public void print(){
    System.out.println(this.name + " " + this.phoneNumber);
}
}

`

PhoneBook Class`

public class PhoneBook {
private static final int CAPACITY = 100;
private Entry entry[]=new Entry[CAPACITY];
private int count; //holds current amount of entries in book

public PhoneBook(){
    count=0; //set initial count value
}
public void add(Entry newEntry){
    if (count > CAPACITY)
        System.out.println("Maximum capacity reached, no more adds allowed");
    entry[count]=newEntry;
    count++;
}
public String find(String pN){
     for (int i=0;i<count;i++) {
            if (entry[i].getPhoneNumber()==pN)
                return entry[i].getName();
        }
        String error="Name not found in phone book.";
        return error;
}
public void print(){
    for (int i=0; i<count;i++)
        entry[i].print();
}
}`

1 个答案:

答案 0 :(得分:0)

在主要类的While循环中:

     while (infile.hasNext()){
            firstName=infile.next();
            lastName=infile.next();
            fullName=firstName+ " " + lastName;
            phoneNumber=infile.next();
            entry = new Entry(fullName, phoneNumber);
            phonebook.add(entry); 
        }