【问题标题】:Printing Out Object In Java在 Java 中打印出对象
【发布时间】:2015-11-28 17:02:21
【问题描述】:

我有一个file,其内容如下:

5
Derrick Rose
1 15 19 26 33 46
Kobe Bryant
17 19 33 34 46 47
Pau Gasol
1 4 9 16 25 36
Kevin Durant
17 19 34 46 47 48
LeBron James
5 10 17 19 34 47

我试图将票的名称和编号放入票构造函数中的数组中,但是当我实例化票对象并尝试显示它时,我得到以下信息:

Tickets: lottery$Ticket@33909752
Tickets: lottery$Ticket@55f96302
Tickets: lottery$Ticket@3d4eac69
Tickets: lottery$Ticket@42a57993
Tickets: lottery$Ticket@75b84c92

我的票的构造函数中是否有问题,或者如果不先将其设为字符串就无法打印数组?

int lim = scan.nextInt();
scan.nextLine();
for(int i = 0; i < lim; i++)
{
        String name = scan.nextLine();
        String num = scan.nextLine();
        String[] t = num.split(" ");
        int[] tichold = new int[t.length];

        for(int j = 0; j < t.length; j++)
        {
            tichold[j] = Integer.parseInt(t[j]);
        }


        Ticket ticket = new Ticket(name, tichold);
        System.out.println("Ticket: " + ticket);
    }
    scan.close();
}

public static class Ticket
{
    public String name;
    public int[] tarray;

    public Ticket(String name, int[] tarray)
    {
        this.name = name;
        this.tarray = tarray;
    }
}

【问题讨论】:

  • Ticket 中覆盖toString

标签: java object constructor instantiation


【解决方案1】:

为了实现这一点,您需要编写一个覆盖 toString 方法并在其中写入您想要的内容。

    public String toString(){
    return //whatever you need goes here and will be printed when you try and
    //print the object            
    }

【讨论】:

    【解决方案2】:

    您需要为其提供toString 方法。这是示例,您可以使用:

    @Override
    public String toString() {
      return "Ticket{" +
          "name='" + name + '\'' +
          ", tarray=" + Arrays.toString(tarray) +
          '}';
    }
    

    【讨论】:

      【解决方案3】:

      你必须重写继承自 Object 类的 toString 方法:

      @Override
      public String toString(){
      return //Enter the format you require
      }
      

      记住ticket是一个引用变量,所以当你打印出来时,你会得到哈希码以及对象是实例的类的名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-29
        • 1970-01-01
        • 2015-06-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多