2013-03-18 64 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