这段代码是我编写的程序的一部分,这是一本使用向量的联系簿,用于我目前在本学期的数据结构类。在写入另一个从文件中读取的方法之前,我对写入文件没有任何问题。使用此代码,它会反复写入数组的内容而没有结束。即使我退出该计划,它仍将继续写作。到达某条线并重新启动。我把read from file方法作为参考,包括问题就在那里。
public void writeFinalToFile() {
try {
FileWriter fw = new FileWriter("file.txt");
PrintWriter pw = new PrintWriter(fw);
for (int x=0; x<size; x++) {
pw.println(people[x].toString());
}
pw.close();
fw.close();
} catch (IOException e) {
System.out.println("Can not write file?1?");
return;
}
}
public void readInitialFromFile() {
String str;
String[] pieces;
Scanner in =null;
Contact c;
try {
in = new Scanner(new File("file.txt"));
} catch(IOException e) {
System.out.println("File not found");
}
while (in.hasNext()) {
str = in.nextLine();
pieces = str.split(":");
c = new Contact();
c.setName(pieces[0]);
c.setNum(Long.parseLong(pieces[1].trim()));
c.setComment(pieces[2]);
addContact(c);
}
}
示例输出:
vrezh:8182645322:me
arthur:8183252314:brother
vrezh:8182645322:me
arthur:8183252314:brother
永远......在这种情况下,我只在数组中输入了两个元素
按请求添加联系方式
public void addContact(Contact c)
{
if (size==capacity) {
Contact[] tmp = new Contact[capacity+5];
capacity += 5;
for (int i=0; i<size; i++)
tmp[i] = people[i];
people = tmp;
}
people[size++] = c;
}
这是主要的我称之为readInitialFromFile();一旦用户决定退出,我就会写下FinalFoFile的底部。
public static void main(String [] args){
String entry;
long phone;
Scanner input = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
System.out.println("Welcome to Contact Book");
System.out.println("Would you like to use a vector or an ordered vector?");
entry = input.next();
if (entry.contentEquals("vector"))
{
VectorOfContacts newVector = new VectorOfContacts();
Contact newContact;
newVector.readInitialFromFile();
while (!(entry.contentEquals("quit"))){
System.out.println("Please enter your command:");
entry = input.next();
if (entry.contentEquals("add"))
{
newContact = new Contact();
System.out.println("Name?");
entry = input.next();
newContact.setName(entry);
System.out.println("Phone number?");
phone = input1.nextLong();
newContact.setNum(phone);
System.out.println("Contact?");
entry = input.next();
newContact.setComment(entry);
newVector.addContact(newContact);
}
else if (entry.contentEquals("quit"))
{
System.out.println("Writing to file ...");
newVector.writeFinalToFile();
}
}