创建两个Rectangle对象的问题

时间:2013-03-18 01:26:01

标签: java object

我正在尝试做作业,而且我似乎遇到了错误。我必须构建一个矩形并返回周长和区域,矩形默认高度和宽度为1.一切看起来都很好,直到我编译它,然后告诉我main方法必须是静态的。当我将main方法设为静态时,我得到了#34;非静态变量,这不能从静态上下文中引用"错误。关于我需要做些什么来修复它的想法?

package rectangle;
/**
 *
 * @author james
 */
public class Rectangle {
/** Main Method */
    public static void main(String[] args) {
        //Create a rectangle with width and height
        SimpleRectangle rectangle1 = new SimpleRectangle();
        System.out.println("The width of rectangle 1 is " + 
                rectangle1.width + " and the height is " +
                rectangle1.height);
        System.out.println("The area of rectangle 1 is " +
                rectangle1.getArea() + " and the perimeter is " +
                rectangle1.getPerimeter());

        //Create a rectangle with width of 4 and height of 40
        SimpleRectangle rectangle2 = new SimpleRectangle(4, 40);
                System.out.println("The width of rectangle 2 is " + 
                rectangle2.width + " and the height is " +
                rectangle2.height);
                System.out.println("The area of rectangle 2 is " +
                        rectangle2.getArea() + " and the perimeter is "
                        + rectangle2.getPerimeter());



    }

        public class SimpleRectangle {
        double width;
        double height;

        SimpleRectangle() {
            width = 1;
            height = 1;
        }

        //Construct a rectangle with a specified width and height
        SimpleRectangle(double newWidth, double newHeight) {
            width = newWidth;   
            height = newHeight;
        }

        //Return the area of the rectangle
        double getArea() {
            return width * height;
        }
        //Return the perimeter of a rectangle
        double getPerimeter() {
            return (2 * width) * (2 * height);
        }

    }
}

1 个答案:

答案 0 :(得分:1)

您正在尝试在类中创建一个类,这可能不是您想要做的。

要么SimpleRectangle在自己的文件中创建一个类,要么只在getPerimeter类上创建getAreaRectangle个方法,并将Rectangle类重命名为SimpleRectangle(您需要相应地更改源文件名)