java program that works ok no matter what

Discussion in 'Programmer's Corner' started by onebird, Jun 10, 2011.

  1. onebird

    Thread Starter New Member

    Mar 27, 2010
    A few months ago, i made a phonebook program using java, as an assignment. It worked well and I was pleased. Now, I was looking over my code and found something that appeared strange to me. The program is attached in the zip folder. It would store the names in a separate file, also in the zip file. It used the following function to save the names in the file:

    Code ( (Unknown Language)):
    1. public void write() throws IOException{ //writes changes to file
    3.         try{
    4.             myfile=new Formatter(new FileWriter("Phonebook.txt"));
    5.         }
    6.         catch(IOException e){   //terminates program without saving changes
    8.             System.out.println(e.getMessage());
    9.             System.out.println("\nAn error occured whilst trying to save your changes");
    10.             System.out.println("The program will terminate and no changes have been saved");
    11.             System.exit(1);
    13.         }
    14.         for(int i=0;i<list.size();i++){
    16.             Person towrite=list.get(i);
    17.             myfile.format("%s %s\n",towrite.getName(),towrite.getNumber());
    19.         }
    20.         myfile.close();
    21.     }
    list is an object of ArrayList holding objects of type Person(keeps the contact details). When writing to the file the name and number is saved then a carriage return. The name could be a single name, like just "John".

    But on reading, the name was assumed to be name and surname separated by a space,as was the intention at design time, as shown in the piece of code below:

    Code ( (Unknown Language)):
    2. while(infile.hasNext()){
    4.             String takename=(" ";
    5.             String;
    6.             Person more=new Person(takename,takenumber);
    7.             list.add(more);
    9.         }
    infile is of type Scanner and is pointing to Phonebook.txt.
    So the issue is whether the name is a single word or two words, both the
    reading and writing to file operations occur without error, and the program operates normally. How is that?

    Am not sure if I am clear, so if it helps, I have also included the source files in the folder.
    And I don't mind if anyone would want to modify or distribute the program. am always glad to share.