2015-03-31 84 views
0

這個代碼公共靜態最終字符串:不能使用Java創建

public class CommandPrompt { 
    public static void main(String[] args) { 
    public static final String prompt = System.getProperty("user.name")+">"; 
     System.out.println(prompt); 
    } 
    } 

返回此錯誤消息:

CommandPrompt.java:5: error: illegal start of expression 
public static final String prompt = System.getProperty("user.name")+">"; 
^ 
CommandPrompt.java:5: error: illegal start of expression 
public static final String prompt = System.getProperty("user.name")+">"; 
    ^
CommandPrompt.java:5: error: ';' expected 
public static final String prompt = System.getProperty("user.name")+">"; 
      ^
3 errors 

我見過public static final String被使用過,爲什麼我不能用在這裏?

回答

5

說明

不能使用publicstatic的方法中。
兩者都爲類屬性保留:public訪問修飾符static聲明瞭類的作用域變量變量。

糾錯

public class CommandPrompt { 
    public static void main(String[] args) { 
     final String prompt = System.getProperty("user.name")+">"; 
     System.out.println(prompt); 
    } 
} 

public class CommandPrompt { 
    public static final String prompt = System.getProperty("user.name")+">"; 

    public static void main(String[] args) { 
     System.out.println(prompt); 
    } 
} 

相關問題

1

您不能在方法中聲明變量爲publicstatic。將其刪除或移動它的方法塊把它變成一個field

0

這是因爲你只能你的類中創建一流水平的變量,你不說,但外面的方法:)

public class CommandPrompt { 
public static final String prompt = System.getProperty("user.name")+">"; 
public static void main(String[] args) { 
    System.out.println(prompt); 
} 
} 

像這樣的東西應該工作。 See this tutorial for more information

+0

*類級別*(*靜態*)和*實例級*(*非靜態*) – TheLostMind 2015-03-31 08:52:47

1

靜態變量不能在方法中聲明。

它應該在課堂級別上進行挖掘。

請嘗試

public class CommandPrompt { 

public static String prompt; 

public static void main(String[] args) { 

prompt=System.getProperty("user.name")+">"; 

System.out.println(prompt); 

} 

}