【问题标题】:How do I print my an array in a toString() method?如何在 toString() 方法中打印我的数组?
【发布时间】:2014-12-09 00:09:41
【问题描述】:

我正在尝试通过 toString() 打印一个数组,以便我可以将它调用到另一个方法。我到底做错了什么?为什么不编译,什么是更好的解决方案。

public class Applicants
{
    private String applicant[];
    public Applicants()
{
    Application student1 = new Application()
    Application student2 = new Application()
    Application student3 = new Application()
    Application student4 = new Application()
    Application student5 = new Application()
    Application student6 = new Application();

    Application applicant[] = new Application[5];
    applicant[0] = student1;
    applicant[1] = student2;
    applicant[2] = student3;
    applicant[3] = student4;
    applicant[4] = student5;
    applicant[5] = student6;

    for (int index = 0; index < applicant.length; index++)
    {   
         System.out.println(applicant[index]);
    }

}
public String toString(String[] applicant)
{
    String output = new String();
    String total;
    for (int index = 0; index < applicant.length; index++)
    {
        total = System.out.println(applicant[index]);
    }
    return total;
}

}

【问题讨论】:

  • 它无法编译,因为这几乎不是有效的代码:total = System.out.println(applicant[index]);
  • 你正在用完全不同的类型隐藏你的字段变量applicant...这很尴尬。
  • 您是否要覆盖toString()?它们需要具有相同的参数才能做到这一点。
  • 当某些东西没有编译时,编译器会给你提示代码错误的行。通过不提供这些信息,您要求其他人使用比您可用的信息更少的信息来调试您的代码。你认为这公平合理吗?

标签: java arrays tostring


【解决方案1】:

错了三件事,还有一件“嘿,注意”。

  1. 您在构造函数中隐藏了 applicant 字段。 这意味着当您完成构造函数时,您的 String[]null。不全是null,只是null

    您可能打算将private Application[] applicant 声明为您的字段,然后不要在构造函数中重新声明它。

  2. total = System.out.println(applicant[index]); 不是有效语句。 您不能将 void 方法的结果分配给任何东西。您在构造函数中正确设置了它,所以令人惊讶的是您在这里没有正确设置它。

  3. toString 不接受任何参数。使用您的字段。

  4. 请在您的Application 对象上定义toString,因为这将使您的生活更轻松。否则,请从该对象中提取有意义的信息。无论哪种情况,您都将对此进行一些字符串连接,我将其作为练习留给读者。

【讨论】:

    【解决方案2】:

    需要在Application类中声明toString方法:

    public class Application {
    
        @Override
        public String toString() {
           // your code here
        }
     }
    

    注意 Override 注解的使用。这将使编译器检查您实际上是否覆盖了您所说的方法 - 在您当前的代码中,您不是因为 toString 不带任何参数。

    至于 toString 的实现,我会选择 Google Guava

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this.getClass()).add(..).add(..).toString();
     }
    

    查看这里了解更多信息:https://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained

    Guava docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多