如何打印返回区域计算的参数变量的方法?

时间:2016-06-19 00:45:12

标签: java object reference return-type

我正在学习对象,我正在尝试不同的东西来学习。我写了2个方法,其中一个返回一个int,它按我想要的方式工作。但另一个是tuffer 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;
}

}

class Box{
int length;
int width;
int area;

}

1 个答案:

答案 0 :(得分:0)

c.area = c.length*c.area;应为c.area = k.length*k.area;

并且,要在控制台日志中编写对象,您应该为Box实现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()实现的能力。