Search code examples
javadelimitertostring

Custom toString(char) method displaying incorrect result


Here is my code:

    @Override
    public String toString() {
        return "\nCustomer Id: " + this.customerId +
                "\nName: " + this.customerName +
                "\nProjects: " + "\n" + getNumberedProjects();
    }

     public String toString(char delimiter) {
        final String QUOTE = "\"";
        final String EOLN = "\n";
        String output =  Integer.toString(this.customerId) + delimiter +
                         QUOTE + this.customerName + QUOTE + delimiter +
                         Integer.toString(this.customerProjects.size());

      output += EOLN + delimiter;
        for (Project project : customerProjects)
              output += EOLN + delimiter + QUOTE + project + QUOTE;
        output += EOLN;
        return output;
     }

It's called by that part:

public void store(String filename, Repository repository) {
    try (PrintWriter output = new PrintWriter(filename)) {
        output.print(repository.toString(DELIMITER));
        output.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(DAOTextImpl.class.getName()).log(Level.SEVERE, null, ex);
    }        
}

It creates a txt file which looks like that:

enter image description here

But this is what I am expecting:

enter image description here


Solution

  • Please find correction in toString method. lets suppose your Project class has three projectId, projectName and startDate properties.

         public String toString(char delimiter) {
            final String QUOTE = "\"";
            final String EOLN = "\n";
            String output =   (this.customerId) + delimiter +
                             QUOTE + this.customerName + QUOTE + delimiter +
                             Integer.toString(this.customerProjects.size());
    
          output += EOLN ;
            for (Project project : customerProjects){
                  output += QUOTE + project.getProjectId() + QUOTE;
                  output +=   delimiter + QUOTE + project.getProjectName() + QUOTE;
                  output +=   delimiter + QUOTE + project.getStartDate();
            output += EOLN;
            }
            return output;
         }