Question

I'm writing to a .dat-file. This is the code:

    String quit = "";
    while(!quit.equals("quit")){ 


     number = number + 1;
     int pid = number; 
     String firstName = JOptionPane.showInputDialog("Give a first name to the Customer:");
     String lastName = JOptionPane.showInputDialog("Give a surname to the Customer:"); 
     String profession = JOptionPane.showInputDialog("Set the profession of the Customer:");
     quit = JOptionPane.showInputDialog("If you are finished, type quit. Otherwise, press any key:");
     boolean append = true;
     out = new BufferedWriter ( new FileWriter("C:\\Temp\\persons.dat", append));// open the file for writing

     out.write (Integer.toString( pid) );
     out.newLine(); 
     out.write ( firstName );
     out.newLine();
     out.write ( lastName );
     out.newLine();
     out.write (profession);
     out.newLine();
     out.newLine();
 out.close();

If I know f.ex. input John as first name, Smith as last name, builder as profession, this will be the output in the code: 1 John Smith builder

But then, if I run the code again, the pid -> person ID will start at 1 again, but I want it to figure out how many different persons have been inputted, and continue incrementing from there. I'm guessing this can be done very easily, but my mind has stopped working.

Was it helpful?

Solution

Your number variable seem to be local to that method or at least it is initialized to 0 every time you start your program.

What you need to do is to make it a class member and initialize it to the number records available in the output file, i.e. in the constructor of your class could init the member variable number by calling a method, let's call it for example readPersons(), which reads the output file if available, parses it and then determines how many records have been entered till this moment.

This is a functionality you will need - if not already have it - for displaying the persons in your output file.

If you haven't yet then I would suggest to create a class for saving persons:

public class Person {
    int pid;
    String firstName, lastName, profession;
}

Your method for reading the persons should then return a List of Person objects

List<Person> readPersons() {
    List<Person> persons = new ArrayList<Person>();
    // open file for reading
    // read line by line
    // once you have red all data for a person,
    // create a Person object an add it to the List persons
    return persons;
}

Init number with the size of persons

number = readPersons().size();

OTHER TIPS

Every time you run this, number will be re-initialized at 0. In order to make this work you have to read in number from the file before writing the new number to the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top