报错:加了static之后,就报错:Non-static field 'height' cannot be referenced from a static context
public class Rectangle {
int width,height;
int area;
public Rectangle(int w,int h)
{
width=w;
height=h;
area=getArea(w,h);
}
public int getArea(int w,int h)
{
return w*h;
}
public static void drawrect()//不能加static,否则不能调用非静态变量height和width
{
for(int i=0;i<height;i++)
{
for(int j=0;j<width;j++)
{
System.out.print("*");
System.out.print("\n");
}
}
}
public static void main(String[]args)
{
Rectangle r1=new Rectangle(5,6);
System.out.println("The area of r1 is "+r1.area);
//r1.drawrect();
drawrect();
}
}
在Java中,使用关键字
static
将方法或变量声明为静态。静态方法和变量属于类本身,而不是属于类的实例对象。当使用静态方法时,只能直接访问同样被声明为静态的成员变量。在你提供的代码中,height
是一个非静态变量,无法从静态方法中直接访问。要解决这个问题,有以下两种可能的方法:
- 将
height
和width
变量声明为静态变量:private static int height; private static int width; public static void drawrect() { // 方法内部的代码不变 }
- 将
drawrect
方法中的height
和width
参数传递给它:public static void drawrect(int height, int width) { // 方法内部的代码不变 } // 调用方法时传递参数 drawrect(height, width);
选择哪种方法取决于你的需求。如果
height
和width
是整个类的共享属性,可以将它们声明为静态变量。如果它们在每次调用drawrect
时都有可能不同,可以将它们作为参数传递给方法。