This code is part of program I wrote which is a contact book using vectors for a data structures class I am currently in this semester. I had no issues with writing to a file originally until I wrote another method to read from a file. With this code it writes the contents of an array over and over with no end. Even once I have quit the program it will keep writing. Get to a certain line and restarts. I included the read from file method as a reference incase the problem is there.
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);
}
}
Sample output :
vrezh:8182645322:me
arthur:8183252314:brother
vrezh:8182645322:me
arthur:8183252314:brother
Forever... In this case I only entered two elements in the array
Add Contact method per request
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;
}
This is where in main I call readInitialFromFile(); and on the bottom where I writeFinalToFile once the user decides to quit.
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();
}
}