0

I am having a frustrating time partway through a Java assignment. I have the first part completed, which is to:

"Create a class named Rectangle to represent a rectangle. The class contains:

• Two double data fields named width and height that specify the width and height of the rectangle.

• A no-arg constructor that creates a default rectangle with 1 for both width and height.

• A constructor that creates a rectangle with a specified width and height.

• public accessor methods for each property

• A method named getArea() that returns the area of the rectangle.

• A method named getPerimeter() that returns the perimeter."

However, I can't seem to finish the next one, which states:

"Write a static method in your Rectangle class called makeGoldenRectangle that takes as a parameter a double representing the longer side of the rectangle and returns a newly constructed Rectangle that is a golden rectangle (http://en.wikipedia.org/wiki/Golden_ratio). The returned rectangle should have height=the longer side and width=the shorter side."

I have the calculation part of the code, I just can't figure out how to get it to return a "rectangle" object, which is critical for the next part. Does anyone have advice or resources I consult (I'm a novice, so resources that can explain things to a potato if possible).

1
  • You should be able to construct it with new Rectangle() and supply the width and height. Commented Feb 26, 2015 at 0:56

1 Answer 1

3

You can just call the 2 parameter constructor from the static method and return the constructed object instance. Obviously you will have to perform the required calculations first to be able to call the constructor with the right parameters.

So you would get:

public static Rectangle getRectangleWithGoldenRatio(double height) {
    double width = calculateGoldenRatio(height);
    return new Rectangle(width, height);
}

public static double calculateGoldenRatioShortSide(double longSide) {
    // perform calculations
}
Sign up to request clarification or add additional context in comments.

3 Comments

I have new Rectangle (height, result){ height=height; width=result; }; it keeps telling me I need a ; in there, but when I add it then everything gets underlined..
Eh, that's not right. I've never heard of a rectangle made out of a height and a result. You should make very clear what your variables mean. You can call the constructor using result but you cannot name your arguments that way.
Oh, you need to specify double width, double height, you're missing the types of the arguments in the declaration of the constructor; Java is strongly typed!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.