gpt4 book ai didi

java - PhoneBook 类未正确保存 Entry 对象

转载 作者:太空宇宙 更新时间:2023-11-04 14:32:47 26 4
gpt4 key购买 nike

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

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

主要`

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

`

电话簿类`

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

最佳答案

在主类的 While 循环中:

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

关于java - PhoneBook 类未正确保存 Entry 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25944420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com