2012-05-26 28 views
0

我完全不熟悉java。我試圖創建我的第一個程序&我得到這個錯誤。得到非法的表達錯誤開始

E:\java>javac Robot.java 
Robot.java:16: error: illegal start of expression 
public String CreateNew(); { 
        ^
Robot.java:16: error: ';' expected 
public String CreateNew(); { 
        ^
2 errors 

下面是我的程序。

public class Robot { 
    public static void main(String args[]){ 
     String model; 
     /*int year;*/ 
     String status; 

     public String CreateNew() { 
      Robot optimus; 
      optimus = new Robot(); 
      optimus.model="Autobot"; 
      /*optimus.year="2008";*/ 
      optimus.status="active"; 
      return (optimus.model); 
     } 
    } 
} 
+2

就像一個側面說明,通常是一個好主意,當類具有大寫名稱時啓動方法小寫。這是Java約定 – Hawken

回答

4

你試圖定義內的方法(CreateNew的方法(main),你不能用Java做的。將其移出main;並作爲modelstatus似乎是實例變量(不是方法變量),移動它們還有:

public class Robot { 
    // Member variables 
    String model; 
    /*int year;*/ 
    String status; 

    // main method 
    public static void main(String args[]){ 

     // Presumably more stuff here 
    } 

    // Further method  
    public String CreateNew() { 
     Robot optimus; 
     optimus = new Robot(); 
     optimus.model="Autobot"; 
     /*optimus.year="2008";*/ 
     optimus.status="active"; 
     return (optimus.model); 
    } 
} 

基於它的內容,你可能希望CreateNewstatic(因此它可以通過Robot.CreateNew,而不是被稱爲通過Robot實例)。就像這樣:

public class Robot { 
    // Member variables 
    String model; 
    /*int year;*/ 
    String status; 

    // main method 
    public static void main(String args[]){ 

     // Presumably more stuff here 
    } 

    // Further method  
    public static String CreateNew() { 
    //  ^----------------------------- here's the change 
     Robot optimus; 
     optimus = new Robot(); 
     optimus.model="Autobot"; 
     /*optimus.year="2008";*/ 
     optimus.status="active"; 
     return (optimus.model); 
    } 
} 

用作

String theModel = Robot.CreateNew(); 

...儘管你爲什麼要創建一個Robot實例,然後把它扔掉,就回到了model實例成員的值,它是我不清楚。


有點偏離主題,但在Java壓倒性的約定是方法名(靜態或實例),開始與小寫字母,例如createNew而不是CreateNew

+0

@Jeffrey:謝謝,我錯過了他們正在'CreateNew'中使用。 –

+0

@Jeffrey如果我需要在同一個程序中的主要方法,我應該如何寫這個。 – user1419170

+0

@ user1419170:見上。 –

1

在創建CreateNew()之前,您並未關閉主要方法。事實上,我不認爲你的機器人類中有一個主要的方法,你應該只有一個主要的方法來完成整個程序。而你CreateNew應該是一個構造

public class Robot { 
     String model; 
     /*int year;*/ 
     String status; 

     public Robot() { 
      this.model="Autobot"; 
      this.status="active"; 
     } 
    } 
} 

,然後在包含您的主要方法另一個類(或者它可能是在同一個類太):

public class OtherClass { 
    public static void main(String[] args) { 
     Robot optimus = new Robot(); // here you create an instance of your robot. 
    } 
} 

那麼你可以有第二個構造函數,在參數採用這樣的模式和狀態:

0:

public Robot (String m, Status s) { 
     this.model=m; 
     this.status=s; 
} 
在主

最後

Robot prime = new Robot("aName", "aStatus");