Java 如何打印返回面积计算参考变量的方法?

Java 如何打印返回面积计算参考变量的方法?,java,object,reference,return-type,Java,Object,Reference,Return Type,我在学习对象,我在尝试不同的东西来学习它。我已经编写了2个方法,其中一个返回一个int,它可以按照我的要求工作。但另一个是塔弗bc,我做错了,它给出了奇怪的数字。你能帮我怎么写Box calculateArea2吗?(我看了getter和setter,但我们还没有学会这些东西)。这是我的密码 public static void main(String[] args) { Box box1 = new Box(); Box box2 = new Box(); Strin

我在学习对象,我在尝试不同的东西来学习它。我已经编写了2个方法,其中一个返回一个int,它可以按照我的要求工作。但另一个是塔弗bc,我做错了,它给出了奇怪的数字。你能帮我怎么写Box calculateArea2吗?(我看了getter和setter,但我们还没有学会这些东西)。这是我的密码

 public static void main(String[] args) {
    Box box1 = new Box();
    Box box2 = new Box();
    String str = JOptionPane.showInputDialog("Enter a length and width");
    Scanner input = new Scanner(str);

    box1.length = input.nextInt();
    box1.width = input.nextInt();

    int BoxsArea = calculateArea(box1); // calculate box1
    JOptionPane.showMessageDialog(null, " First Box's area is: "+BoxsArea );

    String str2 = JOptionPane.showInputDialog("Enter a length and width");
    input = new Scanner(str2);

    box2.length = input.nextInt();
    box2.width = input.nextInt();

    Box box3 = new Box();
    calculateArea2(box2); // Calculate box 2

    JOptionPane.showMessageDialog(null, " Second Box's area is: "+box3 );

}

public static int calculateArea(Box k){
    return k.length* k.width;
}


public static Box calculateArea2(Box k){
    Box c = new Box();
    c.area = c.length*c.area;
    return c;
}
}


}

c.area=c.length*c.area应该是
c.area=k.length*k.area

而且,要在控制台日志中写入对象,您应该为如下框实现
toString()
方法:

@Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Box [length=");
            builder.append(length);
            builder.append(", width=");
            builder.append(width);
            builder.append(", area=");
            builder.append(area);
            builder.append("]");
            return builder.toString();
        }

您可以使用
box.toString()
或甚至使用
box
在控制台中写入对象。不同的IDE提供了生成toString()实现的功能,可以查看类。

为什么在扫描器的构造函数中有一个字符串作为参数(
newscanner(str)
)?无论如何,您的问题一点也不清楚。请重写Box类的
公共字符串toString()
方法,以便在将Box对象传递到println方法时,它将显示有意义的文本,告诉您Box对象的状态(其长度、宽度和面积).@Gendarme Bc我想重复我所知道的,这有助于回忆过去的经验教训,@装满鳗鱼的气垫船你能解释一下为什么我需要使用Ovirride toString方法吗?为什么默认的toString方法不足以编写我的对象,为什么该方法需要这样的东西;公共字符串toString(){return”“+area;}它仍在提供对象位置的内存:/Updated my answer。
@Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Box [length=");
            builder.append(length);
            builder.append(", width=");
            builder.append(width);
            builder.append(", area=");
            builder.append(area);
            builder.append("]");
            return builder.toString();
        }