我仍然不完全理解我需要在項目的.java文件中使用「public static void main(String [] args)」標頭的位置。你需要把這個頭文件放在包的每個.java文件中嗎?將獨立的java文件轉換爲作爲項目包一部分的文件?
我一直在跟着我的書中的第3章,將下載的獨立書籍源文件拖放到我的項目包中,但是我的包中的一些.java文件不喜歡那樣「public static void main (String [] args)「語句,即使我的開啓和關閉花括號在正確的位置。下面是這些文件中的一個(ERROR(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
的誤差(S)上來後,我加入了「公共靜態無效的主要(字串[] args )「到現有的Rectangle.java文件。任何想法爲什麼發生這種情況?
不,你不應該。主頭必須只存在於包的一個類中,因爲編譯器只運行一個包含主語句的類。 –