打印内存地址而不是java中的数据

时间:2015-08-26 01:52:32

标签: arrays memory-address points

所以我正在尝试设置一个包含x y坐标的数组。 该程序似乎工作,但我的打印结果是内存地址。 这是我的代码:

static class Point{
    int x;
    int y;
    @Override
    public String toString() {
        return  x + " " + y;
    }
}

public static Object thePoints( int x, int y){
    Point[] mypoints = new Point[10];
    for (int i = 0; i < mypoints.length; i++){
       mypoints[i] = new Point();
    }   
    mypoints[0].x = 200;
    mypoints[0].y = 200;
    return mypoints;
}

public static void main(String args[]) {
    Object thing = thePoints(0,0);

    System.out.print(thing);
    }
}

输入表示赞赏。

2 个答案:

答案 0 :(得分:2)

您正在Point[]方法中打印出main()类型的数组,与其显示的内容相反。解决此问题的一种快速方法是使用Arrays.toString()。尝试将main()方法中的代码更改为:

public static void main(String args[]){
    Object thing = thePoints(0,0);

    System.out.print(Arrays.toString((Point[])thing));
}

如果您还将Point.toString()重构为以下内容,那么您会得到一些相当不错的输出:

static class Point{
    int x, y;

    @Override
    public String toString() {
        return  "(" + x + ", " + y + ")";    // print out a formatted ordered pair
    }
}

<强>输出:

[(200, 200), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]

答案 1 :(得分:0)

您正在打印物品&#39;直。 System.out.print()仅适用于字符串和原始数据类型,因此如果您想打印有关&#39;对象事物的信息。你必须使用为类&#39; Point&#39;声明的toString()方法。

bigint
相关问题