自定义toString(char)方法显示不正确的结果

时间:2017-10-30 10:57:39

标签: java delimiter tostring

这是我的代码:

if (myComparator.compare(people.get(i), p) > 0 ) {

该部分称之为:

    @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;
     }

它创建一个txt文件,如下所示:

enter image description here

但这是我所期待的:

enter image description here

2 个答案:

答案 0 :(得分:0)

请在toString方法中找到更正。假设您的Project课程有三个projectIdprojectNamestartDate属性。

     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;
     }

答案 1 :(得分:0)

我可以从您的代码和结果中推断出两个问题:

  • 显然,来自toString()类的Project方法不会返回您希望返回的内容。你也覆盖了它吗?因为在这一行:

    output += EOLN + delimiter + QUOTE + project + QUOTE;
    

    你好像期待project翻译成类似的东西   "\"" + project.getId() + "\",\"" + project.getName() + "\",\"" + project.getStart() + "\""
    实际上它正在返回这样的东西:
      "\nProject ID: " + project.getId() + " Project Name: " + project.getName() + " Start: " + project.getStart() + "\n"
    您需要覆盖Project#toString()以使其返回您想要的内容。

  • 您似乎在实际代码中使用的是QUOTE而不是EOLN(而不是您向我们展示的代码)。由于此行output += EOLN + delimiter;正在打印此",,因此唯一的解释是您的实际代码为output += QUOTE + delimiter;。可能是一个错字,只需纠正它。