[英]Can't create a public static final String in 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
,為什么不能在這里使用它呢?
說明
您不能在方法內部使用public
和static
。
兩者都保留用於類屬性: 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);
}
}
相關問題
您不能在方法內將變量聲明為public
變量或static
變量。 刪除它們或將其移出方法塊以將其轉換為field
靜態變量不能在方法中聲明。
應該在課堂上講課。
請試試
public class CommandPrompt {
public static String prompt;
public static void main(String[] args) {
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);
}
}
這樣的事情應該起作用。 有關更多信息,請參見本教程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.