0

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();
        }
     }
Vrezh Gulyan
  • 198
  • 2
  • 6
  • 4
    _"Even once I have quit the program it will keep writing"_ seriously? your PC is hounted – Baby Oct 17 '14 at 02:29
  • how do you call your method `readInitialFromFile()`? – DnR Oct 17 '14 at 02:32
  • How do you call `writeFinalToFile()`? Please use a debugger and step through the call sequence to see why it is repeated. As it is, your post does not provide enough information for us to help you. Also, what is the connection between `addContact()` and the `people` array? – Ken Y-N Oct 17 '14 at 02:34
  • @TheQuickBrownFox mac* lol I leave eclipse open, I assume it running in the background somewhere.. not sure.. upvote it and lets see if someone has an answer! Id appreciate it. – Vrezh Gulyan Oct 17 '14 at 02:40
  • @DnR I call it in main before I ask if they want to add delete a contact etc. to see if there is already a file containing contacts. – Vrezh Gulyan Oct 17 '14 at 02:42
  • @KenY-N I call writeFinalToFile(); whenever the user decides to quit the program which ends the loop of asking for a command. I'll edit my code so you can see the addContact() method, it just checks that size isnt greater than capacity and then adds the new contact into the array. – Vrezh Gulyan Oct 17 '14 at 02:45
  • DnR (presumably) and definitely I meant "please show us the code where you call these functions"; your currently posted code has nothing particularly untoward, although I would use an `ArrayList` or the like instead of a plain array. – Ken Y-N Oct 17 '14 at 02:51
  • 1
    step debuggers exist for a reason! learn to use the one you have! –  Oct 17 '14 at 02:58
  • @KenY-N Sorry brother I am new to the website I didn't want to post too much code or anything like that. I edited my post and at the bottom added the main method that starts the program, the part where a new contact is made and at the end where I write the final result to a file. – Vrezh Gulyan Oct 17 '14 at 02:58
  • What is the fascination with `Scanner` all of a sudden, did new crapper text books come out this fall? `Scanner` is **not** the idiomatic way to read from a file in Java, especially reading lines at a time! It has way to many side effects! –  Oct 17 '14 at 03:02
  • 1
    And this is extremely disjointed and convoluted, what Type is `entry.contentEquals()` is it a `StringBuffer/Builder` or something else? There is only enough code here to suggest that the root cause isn't shown. –  Oct 17 '14 at 03:04
  • @JarrodRoberson point taken about the debugger, will get on that. What is a better method of reading a file in your opinion ? I was advised to use Scanner and thats the only reason why its in there. – Vrezh Gulyan Oct 17 '14 at 03:04
  • `BufferedReader` is the idiomatic way to read a file line by line. Advice to use `Scanner` is usually wrong if it isn't some quick and dirty example of reading from `System.in`. Advice to use `StringTokenizer` for anything should be ignored as well. –  Oct 17 '14 at 03:05
  • @JarrodRoberson I see, Ill look into BufferedReader, I added the beginning of my main.. which shows that entry is a string. Sorry for the trouble – Vrezh Gulyan Oct 17 '14 at 03:07
  • `String.equalsIgnoreCase()` is what you want most of the time unless you require case sensitivity, then use `String.equals()` since 1996 I haven't ever need to use `String.contentEquals()` because comparing `String` to `StringBuffer/Builder` or other `CharSequence` is rarely done. And the idiomatic way to compare literals to `String` objects is `"vector".equals(entry);` this avoids a useless check for `null` or `NullPointerException` being thrown. –  Oct 17 '14 at 03:10
  • Also ignore suggestions to use `Vector` or `Hashtable` use `List` or `Map`; this has been the case since 1999! –  Oct 17 '14 at 03:14
  • 1
    You do not need both a `Scanner input` and `Scanner input1`. I haven't a clue what happens if you have two active on the same file, but I'm betting it's not good. And _please, please_ step through your code in Eclipse's debugger; it will be far quicker than all the back-and-fore here. – Ken Y-N Oct 17 '14 at 03:14

0 Answers0