显示数组的值。获取奇怪的值

时间:2019-10-15 08:18:31

标签: java arrays for-loop

我想给TockaXY类型的k个随机点。 TockaXY定义为:

 public static class TockaXY {

      private float x;
      private float y;

      public TockaXY(float x, float y) { 
          this.x = x;
          this.y = y;  
      }

函数是这样的:

 public static TockaXY[] randomCentri(int k, int lowerBound, int upperBound) {
       TockaXY[] arrayCentri = new TockaXY[k];
          for (int i = 0; i < k; i++) {
              float x = (float)(Math.random() * (upperBound - lowerBound) + lowerBound)/100;
              float y = (float)(Math.random() * (upperBound - lowerBound) + lowerBound)/100;
              TockaXY point = new TockaXY(x, y);
              arrayCentri[i]=point;
          }
          System.out.println(" Random centri: " + arrayCentri);
          return arrayCentri;

      }

但是我得到了

Random centri: [LTest$TockaXY;@6ce253f1

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

现在,您仅看到指针的表示。 Java内部将在Emulated Performance Graphics上调用.toString()。

Software类中实现toString()方法并遍历数组,将数组的每个条目转换为String。

答案 1 :(得分:1)

您需要在TockaXY类中添加toString方法

@Override
    public String toString() {
        return "TockaXY{" + "x=" + x + ", y=" + y + '}';
}

并在打印时使用Array.toString

System.out.println(" Random centri: " + Arrays.toString(arrayCentri));

或使用循环打印每个数组元素

for(TockaXY point: arrayCentri){
    System.out.println(point);
}