增强循环无法正确打印

时间:2013-10-12 08:27:09

标签: java arrays loops

我正在尝试使用增强的for循环从数组中打印出我的数据,但它却带有垃圾。请帮助,提前谢谢。

ArrayList array = 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

3 个答案:

答案 0 :(得分:0)

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

public String toString() {
    return  number+" "+name;
}

答案 1 :(得分:0)

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

@Override 
public String toString()
{ 
  return "Your String"; 
}

答案 2 :(得分:0)

默认情况下,toString类中的Object方法会打印类名和其他一些nums,您可以覆盖它以打印您想要打印的内容,所以只需执行以下操作:< / p>

  @Override 
   public String toString()
  { 
      return "returning something"; 
  }