-2

我正在尝试使用增强的 for 循环从数组中打印出我的数据,但结果是垃圾。请帮忙,提前谢谢你。

ArrayList 数组 = new ArrayList();

    //For loop to input names
    for(int i=0; i < 3; i++)
    {   
        System.out.print("Enter name of Player " + i +":");
        String startName = keyboard.nextLine();
        System.out.print("Enter jersey number of Player " + i +":");
        int playNum = keyboard.nextInt();
        startName = keyboard.nextLine();

        //Make objects and add to array
        HockeyPlayer p = new HockeyPlayer(startName, playNum);
        array.add(p);
    }
    keyboard.close();

循环的代码是:

System.out.println("The players are...");

        for(HockeyPlayer val : array)
        {
            System.out.println(val);
        }

它最终打印出这样的东西......我该如何解决它?

Please enter the names and jersey numbers of 3 hockey players.
Enter name of Player 0:Joeasdas
Enter jersey number of Player 0:213
Enter name of Player 1:Baskdja
Enter jersey number of Player 1:121
Enter name of Player 2:djasklaj
Enter jersey number of Player 2:455
The players are...
HockeyPlayer@3f84246a
HockeyPlayer@7c72cbb9
HockeyPlayer@549d1e83
4

3 回答 3

0

您必须覆盖 HockeyPlayer 类中的 toString 方法。例如:

public String toString() {
    return  number+" "+name;
}
于 2013-10-12T08:30:01.757 回答
0

HockeyPlayer@3f84246a 表示您没有覆盖 toString 方法。只需在 HockeyPlayer 中声明这样的方法:

@Override 
public String toString()
{ 
  return "Your String"; 
}
于 2013-10-12T08:30:51.880 回答
0

默认情况下toString,类中的方法Object打印类名和其他一些数字,您可以覆盖它以打印您希望它打印的内容,因此只需执行以下操作:

  @Override 
   public String toString()
  { 
      return "returning something"; 
  }
于 2014-02-18T04:05:41.743 回答