java program that works ok no matter what

Thread Starter

onebird

Joined Mar 27, 2010
16
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:

Rich (BB code):
public void write() throws IOException{	//writes changes to file 

		try{
			myfile=new Formatter(new FileWriter("Phonebook.txt"));
		}
		catch(IOException e){	//terminates program without saving changes

			System.out.println(e.getMessage());
			System.out.println("\nAn error occured whilst trying to save your changes");
			System.out.println("The program will terminate and no changes have been saved");
			System.exit(1);

		}
		for(int i=0;i<list.size();i++){

			Person towrite=list.get(i);
			myfile.format("%s %s\n",towrite.getName(),towrite.getNumber());

		}
		myfile.close();
	}
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:

Rich (BB code):
while(infile.hasNext()){

			String takename=(infile.next()+" "+infile.next());
			String takenumber=infile.next();
			Person more=new Person(takename,takenumber);
			list.add(more);

		}
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 src.zip folder.
And I don't mind if anyone would want to modify or distribute the program. am always glad to share.
 

Attachments

Top