I'm writing a simple Java program, to familiarise myself with methods, that logs the people a person has met. For instance, if I meet Alison in London, I would log the following (Format: name,gender,when,where):
Alison,F,apr2013,London
The program is built up as follows:
The user is presented with different opportunities:
- Log person
- Search for all people named [name]
- Search for all people met [place]
- Get a list of available commands
- Quit
Here is the skeleton of my code:
public void chooseCommand() throws FileNotFoundException {
System.out.println("Enter command: ");
text = input.next();
myCommand = Integer.parseInt(text);
while (myCommand !=5) {
if (myCommand == 1) {
writeToFile(); //Log new person
}
// Search for person type
else if (myCommand == 2) {
searchFor(); // Search for person by name
}
// Search for place
else if (myCommand == 3) {
searchFor(); // Search for person by place
}
// help
else if (myCommand == 4) {
showCommands(); // get a list of available commands
}
else if (myCommand == 5) {
exit();
}
// default
else {
System.out.println("Command not found");
}
}
}
This works just fine. However, after I choose one of the five options (log new person, search for name, search for place, help, quit), I would like to go back to the chooseCommand() method, so as to get the same options presented again, instead of having the initially chosen method loop infinitely. That is to say, after I log a new person, I want to be able to get new options, as opposed to having to log new people for all eternity, without killing the program.
// REGISTER
public void writeToFile() {
// Write to file
try {
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
System.out.println("Enter sighting: ");
for (int i = 0; i < personBlank.length; i++) {
System.out.println(personInfo[i] + ": ");
personEntry = input.next();
personBlank[i] = personEntry;
}
// change to toString() method
observed = personBlank[0] + "," + personBlank[1] + "," + personBlank[2] + "," + personBlank[3];
if (observed.equals(escape)) {
exit();
}
else {
output.write(observed); // log new person
output.newLine();
output.close();
}
back();
}
catch (IOException e){
e.printStackTrace();
}
}
Any help on this is highly appreciated!