0

宿題をしようとしていますが、エラーが発生しているようです。長方形を作成し、周囲と面積を返す必要があります。長方形のデフォルトの高さと幅は 1 です。コンパイルするまではすべて問題ないように見えますが、メイン メソッドは静的でなければならないと言われます。メイン メソッドを静的にすると、「非静的変数は静的コンテキストから参照できません」というエラーが表示されます。それを修正するために何をする必要があるかについてのアイデアはありますか?

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);
        }

    }
}
4

1 に答える 1

1

クラス内にクラスを作成しようとしていますが、これはおそらくあなたがやりたいことではありません。

SimpleRectangle独自のファイルでクラスを作成するか、クラスのメソッドを作成してgetPerimeterクラスの名前を次のように変更します(それに応じてソースファイル名を変更する必要があります)getAreaRectangleRectangleSimpleRectangle

于 2013-03-18T01:31:12.087 に答える