How to get the return of a class method printed in main in Java?

Viewed 177

I am just learning now class and constructors in Java but I can't understand why I can't print out a combined value from other methods. This is my code in main.java :

public static void main(String[] args) {

    Wall height = new Wall ();
    Wall width = new Wall ();
    Wall area = new Wall();


    height.setHeight(5);
    System.out.println("height = " + height.getHeight());
    width.setWidth(4);
    System.out.println("width = " +width.getWidth());
    System.out.println("area = " +width.getWidth()*height.getHeight());
    System.out.println(area.getArea());
    System.out.println("AREA      =     " + area );

}

and this is my code in Wall Class :

public class Wall {

private double height;
private double width;

public Wall () {
    this.height = height;
    this width = width;
}

    public Wall (double height, double width){
        if (height <= 0 || width <= 0) {
            this.height = 0;
            this.width = 0;
        }

    }

        public double getHeight () {
            return this.height;
        }
        public double getWidth () {
            return this.width;
        }
        public void setHeight (double height){
        this.height = height;
    }
    public void setWidth (double width){
        this.width = width;
    }

    public double getArea () {
        this.height = height;
        this width = width;
    double area = getHeight()*getWidth();

        return area;
    }

I have problems with the last method getArea, as it prints out 0.0 as if height and width are not set. What am I missing?

2 Answers

Problem

You have set width and height in different objects and trying to find the the area from a different object.

Solution

You need to set these values to the same object as shown below:

Wall wall = new Wall ();

wall.setHeight(5);
System.out.println("height = " + wall.getHeight());
wall.setWidth(4);
System.out.println("width = " + wall.getWidth());
System.out.println("area = " + wall.getWidth() * wall.getHeight());
System.out.println(wall.getArea());

You have three different Wall objects - the area won't be affected by setting values on height or width. It seems like you meant to have one wall:

Wall wall = new Wall();

wall.setHeight(5);
System.out.println("height = " + wall.getHeight());
wall.setWidth(4);
System.out.println("width = " +wall.getWidth());
System.out.println("area = " + wall.getWidth() * wall.getHeight());
System.out.println(wall.getArea());
Related