这个算法有什么错误?我该如何解决? Eclipse告诉我主要的错误
area c1 = new area();
import java.awt.Rectangle;
public class ClasseRettangolo {
public class area {
Rectangle box = new Rectangle(5 , 10, 15, 20);
public double surface() {
return ( box.getHeight() * box.getWidth());
}
}
public class perimeter {
Rectangle box = new Rectangle(5 , 10, 15, 20);
public double outline() {
return ((box.getHeight() + box.getWidth())* 2);
}
}
public static void main(String[] args){
area c1 = new area();
perimeter c2 = new perimeter();
System.out.println("The area of the Rectangle is: " + c1.surface());
System.out.println("The perimeter of the Rectangle is: " + c2.outline());
}
}
答案 0 :(得分:3)
制作area
和perimeter
类static
public static class area { .. }
public static class perimeter { .. }
或 您必须实例化ClasseRettangolo
类,然后实例化嵌套类。
new ClasseRettangolo().new area();
new ClasseRettangolo().new perimeter();
与问题无关:
答案 1 :(得分:2)
问题是你正在使用非静态内部类。看起来你是一个新手,因此,暂时遵守这个简单的规则:每个类应该被定义为自己的.java文件中的顶级类。一旦了解了简单类的工作原理,请阅读the tutorial about nested classes。
另外,尊重Java命名约定:类以大写字母开头。
答案 2 :(得分:0)
将区域类和周边类视为静态类,如下所示
import java.awt.Rectangle;
public class ClasseRettangolo {
public static class area {
Rectangle box = new Rectangle(5 , 10, 15, 20);
public double surface() {
return ( box.getHeight() * box.getWidth());
}
}
public static class perimeter {
Rectangle box = new Rectangle(5 , 10, 15, 20);
public double outline() {
return ((box.getHeight() + box.getWidth())* 2);
}
}
public static void main(String[] args){
area c1 = new area();
perimeter c2 = new perimeter();
System.out.println("The area of the Rectangle is: " + c1.surface());
System.out.println("The perimeter of the Rectangle is: " + c2.outline());
}
}
了解更多有关静态内部类的信息
答案 3 :(得分:0)
班级area
和perimeter
属于班级ClasseRettangolo
。因为它们不是静态的而是内部类,所以如果没有外部类的实例,则无法创建它们的实例。即使这样,名称也不会是area
,而是ClasseRettangolo.area
。