我一步一步地跟着我们在课堂上如何做到这一点,但是当我尝试编译时,我得到了以下错误:
错误:非静态变量,无法从静态上下文中引用。
受质疑的是 cir1 = new Circle(); 和 cir2 = new Circle();
我理解错误意味着我只是很难看到我的错误,因为它与我们在课堂上所做的完全相同(或者我认为......)
public class CircleDemo{
public static void main(String[] args){
Circle cir1, cir2;
cir1 = new Circle();
cir2 = new Circle();
cir1.setRadius(3.0);
cir2.setRadius(11.01);
System.out.println("Area of the first circle: " + cir1.findArea());
System.out.println("Circumference of the first circle: " + cir1.findCircumference());
System.out.println("Area of the second circle: " + cir2.findArea());
System.out.println("Circumference of the second circle: " + cir2.findCircumference());
}
public class Circle{
//Instance Variables
private double PI = 3.1459;
private double radius;
//Methods
public Circle ( ) { }
//get method (Accessor Methods )
public double getRadius ( ) {
return radius;
}
//set method (Mutator Methods)
public void setRadius (double r) {
radius=r;
}
public double findArea ( ) {
return PI*radius*radius; //area= pi r squared
}
public double findCircumference ( ) {
return 2 * PI * radius;
}
}//end Circle
}
如果有人能帮助我理解我做错了什么,我将不胜感激!谢谢。
答案 0 :(得分:0)
这似乎是一个简单的括号错误。也许是滥用关键字" public"在Circle类定义中。以下是修订后的代码:
public class CircleDemo {
public static void main(String[] args){
Circle cir1, cir2;
cir1 = new Circle();
cir2 = new Circle();
cir1.setRadius(3.0);
cir2.setRadius(11.01);
System.out.println("Area of the first circle: " + cir1.findArea());
System.out.println("Circumference of the first circle: " + cir1.findCircumference());
System.out.println("Area of the second circle: " + cir2.findArea());
System.out.println("Circumference of the second circle: " + cir2.findCircumference());
} //Added this bracket
}
class Circle { //removed the word "public" I'll this explain below
//Instance Variables
private double PI = 3.1459;
private double radius;
//Methods
public Circle () {}
//get method (Accessor Methods )
public double getRadius ( ) {
return radius;
}
//set method (Mutator Methods)
public void setRadius (double r) {
radius=r;
}
public double findArea ( ) {
return PI*radius*radius; //area= pi r squared
}
public double findCircumference ( ) {
return 2 * PI * radius;
}
} //Removed an extra bracket here
一些不正确的括号导致错误。此外,如果Circle类与CircleDemo类在同一文件中定义,则Circle类必须不定义为" public",因为这会导致错误。如果Circle类在其自己的文件中定义,那么它可以是" public"。我对此进行了测试以确保其正常工作。