我仍然不完全理解在项目的 .java 文件中需要在哪里使用“public static void main(String[] args)”标头。您是否需要将该标头放在包的每个 .java 文件中?
我一直在关注我书中的第 3 章,将下载的独立书籍源文件拖放到我的项目包中,但是我的包中的一些 .java 文件不喜欢那个“public static void main(String[] args)" 声明,即使我的开始和结束花括号在正确的位置。这是其中一个文件的示例(代码注释中描述了错误(S)):
public class Rectangle
{
public static void main(String[] args){
private double length;//ERROR: illegal start of expression
private double width;
/**
* Constructor
*/
public Rectangle(double len, double w)
{
length = len;
width = w;
}
/**
* The setLength method accepts an argument
* that is stored in the length field.
*/
public void setLength(double len)
{
length = len;
}
/**
* The setWidth method accepts an argument
* that is stored in the width field.
*/
public void setWidth(double w)
{
width = w;
}
/**
* The set method accepts two arguments
* that are stored in the length and width
* fields.
*/
public void set(double len, double w)
{
length = len;
width = w;
}
/**
* The getLength method returns the value
* stored in the length field.
*/
public double getLength()
{
return length;
}
/**
* The getWidth method returns the value
* stored in the width field.
*/
public double getWidth()
{
return width;
}
/**
* The getArea method returns the value of the
* length field times the width field.
*/
public double getArea()
{
return length * width;
}
}//end of: public static void main(String[] args)
}//end of: public class Rectangle ERROR: class, interface, or enum expected
在我将“public static void main(String[] args)”添加到现有的 Rectangle.java 文件后,出现了 ERROR(S)。知道为什么会这样吗?