日期:2014-05-20  浏览次数:20696 次

JAVA程序找不到主方法,求解
public class Test{
protected double x;
protected double y;
public Test(){
x=0;
y=0;
}
public Test(double x,double y){
this.x=x;
this.y=y;
}
public void setX(double x){
this.x=x;
}
public double getX(){
return x;
}
public void setY(double y){
this.y=y;
}
public double getY(){
return y;
}
public void print(){
System.out.println(x+" "+y);
}
}
class Circle extends Test{
protected double r;
public Circle(){
r=0;
}
public Circle(double r,double x,double y){
this.x=x;
this.y=y;
this.r=r;
}
public void setR(double r){
this.r=r;
}
public double getR(){
return r;
}
public void area(){
System.out.println(Math.PI*r*r);
}
}
class Cylinder extends Circle{
protected double h;
public Cylinder(){
h=0;
}
public Cylinder(double x,double y,double r,double h){
this.x=x;
this.y=y;
this.r=r;
this.h=h;
}
public void setH(double h){
this.h=h;
}
public double getH(){
return h;
}
public void volume(){
System.out.println(Math.PI*r*r*h);
}
public static void main(String[] args){
Cylinder cylinder=new Cylinder(1,4,3,10);
cylinder.print();
cylinder.area();
cylinder.volume();
}
}
程序运行,显示找不到主方法,程序哪里有错误?
本人JAVA菜鸟
------解决方案--------------------
main方法必须写在public类中。
------解决方案--------------------
这个问题是这样的:
1. 一个 java 源文件中可以定义一个或多个类。
2. 如果一个 java 源文件中有多个类,那么只能有一个类被定义为 public 型,并且该类的名称必须和该 java 源文件的名称相同。比如,现有一个 test.java 文件,那么如果该文件中有公有类,那么类的名称必须为 test ,或者,该文件中根本没有公有类也行。
3.main方法必须位于 public 类中。

你的程序中,main 方法写在 Cylinder 类中,但是 Cylinder 类非公有; Test 类是公有类,但是里面又没有 main 方法。所以,编译通不过。