2013-03-18 62 views
0

我正在嘗試做我的功課,而且我似乎遇到了錯誤。我必須建立一個矩形並返回周長和麪積,矩形的默認高度和寬度都是1.一切看起來都不錯,直到我編譯它,然後我被告知主要方法必須是靜態的。當我使主要方法爲靜態時,然後我得到「無法從靜態上下文中引用的非靜態變量」錯誤。我需要做什麼來解決它的任何想法?創建兩個Rectangle對象的問題

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

    } 
} 
+2

請確保您將包含* exact *錯誤消息,即將其剪切並粘貼到問題中。 – Dancrumb 2013-03-18 01:29:06

+1

並且請在這裏顯示一個明顯的註釋,例如發生編譯器錯誤的'****** error here ****'。 – 2013-03-18 01:30:11

+0

嗯.. ahhhh .. ummmm ...沒關係...愚蠢的支架.... – user2154095 2013-03-18 01:30:33

回答

1

你正試圖在一個類中創建一個類,這可能不是你想要做的。

要麼讓SimpleRectangle在自己的文件中的類,或者只是讓對RectanglegetPerimetergetArea方法和Rectangle類重命名爲SimpleRectangle(你要相應地改變你的源文件名)

+0

就是這樣。我錯過了一個支架,一旦我把它放進去,代碼就編譯完成,並做到了我想要的。謝謝你們。 – user2154095 2013-03-18 01:53:24