vendredi 19 septembre 2014

PhoneBook class not properly holding Entry objects


Vote count:

0




I have a program that reads from a file which contains first names, last names and phone numbers in this format: John Doe 123-456-7890


The program reads these as Strings and enters them into the Entry class and then adds the Entry object to the PhoneBook. There are additional print functions. Right now when the I print it simply is printing the last entry 56 times (there are 56 "entries" in the txt file). For whatever reason the entries are being passed correctly to the Entry class because I can print those properly but when I add them to the PhoneBook and try to print it only prints the last entry. Any help would be appreciated on how I am screwing this up. Thanks!


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();


}
}`


Entry Class`



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();
}
}`


asked 1 min ago







PhoneBook class not properly holding Entry objects

Aucun commentaire:

Enregistrer un commentaire