Java:成功构建,但输出为“user_package.Point@68e26d2e” [英] Java: successful build but the output is "user_package.Point@68e26d2e"

查看:106
本文介绍了Java:成功构建,但输出为“user_package.Point@68e26d2e”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习java并尝试执行一个简单的脚本。我有一个类 Point 如下:

I am learning java and trying to execute a simple script. I have a class Point as the following:

package user_package;

public class Point {
    float x;
    float y;
    float z;

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

    public static Point add(Point p1, Point p2){
        return new Point(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z);
    }
}

然后我有这样的主文件: p>

Then I have the main file like this:

import user_package.Point;
import static user_package.Point.add;

class Tutorial{
    public static void main(String[] args){

        float x1 = 1, y1 = 1, z1 = 1;
        float x2 = 2, y2 = 2, z2 = 2;

        Point p1 = new Point(x1, y1, z1);
        Point p2 = new Point(x2, y2, z2);

        Point p3 = add(p1, p2);

        System.out.println(p3);
    }
}



我在Netbeans中执行此操作。它给我没有错误,并且构建成功,但输出是:

I do this in Netbeans. It gives me no errors and the build is successful but the output is:

user_package.Point@68e26d2e

我试图搜索自己,但没有发现。

I tried to search myself but nothing found. Please tell me what the problem is and how I can solve it.

推荐答案

当你写

 System.out.println(p3);

toString()

由于您没有提供任何实现,

Since you didn't provide any implementation there,

您必须删除<$ Point 类中的 toString()方法。

You have to ovveride the toString() method in your Point class.

根据toString()的文档< a>

As per docs of toString()


返回对象的字符串表示形式。一般来说,toString方法返回一个文本表示此对象的字符串。

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.

所以

 user_package.Point@68e26d2e  is the textual representation of Point class.

要获取所需的输出,请将逻辑写入覆盖 toString 方法在Object类中,并返回该字符串。

To get the required output, write the logic in overridden toString method in Object class and return the string there.

package user_package;

    public class Point {
        float x;
        float y;
        float z;

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

        public static Point add(Point p1, Point p2){
            return new Point(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z);
        }

        @Override
        public String toString() {
          StringBuilder result = new StringBuilder();
             result.append(this.x).append(",");  
             result.append(this.y).append(",");
             result.append(this.z)
             return result.toString();
        }
    }

这篇关于Java:成功构建,但输出为“user_package.Point@68e26d2e”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆