[英]Can't create a public static final String in java
This code: 这段代码:
public class CommandPrompt {
public static void main(String[] args) {
public static final String prompt = System.getProperty("user.name")+">";
System.out.println(prompt);
}
}
Returns this error message: 返回此错误消息:
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
I have seen public static final String
been used before, why can't I use it here? 我以前看过public static final String
,为什么不能在这里使用它呢?
Explanation 说明
You can't use public
and static
inside a method. 您不能在方法内部使用public
和static
。
Both are reserved for class attributes: public
is an access modifier and static
declares a class scoped variable. 两者都保留用于类属性: public
是访问修饰符 , static
声明类范围的变量。
Correction 更正
public class CommandPrompt {
public static void main(String[] args) {
final String prompt = System.getProperty("user.name")+">";
System.out.println(prompt);
}
}
or 要么
public class CommandPrompt {
public static final String prompt = System.getProperty("user.name")+">";
public static void main(String[] args) {
System.out.println(prompt);
}
}
Related question 相关问题
You cannot declare variables as public
or static
within a method. 您不能在方法内将变量声明为public
变量或static
变量。 Either remove them or move it out of the method block to turn it into a field
删除它们或将其移出方法块以将其转换为field
Static variables cannot be declared in a method. 静态变量不能在方法中声明。
It should be delcared in the class level. 应该在课堂上讲课。
Please try 请试试
public class CommandPrompt {
public static String prompt;
public static void main(String[] args) {
prompt=System.getProperty("user.name")+">";
System.out.println(prompt);
}
}
It's because you can only create class level variable inside your class, you don't say, but outside of a method :) 这是因为您只能在类内部创建类级别的变量,而不必说,但是可以在方法之外:)
public class CommandPrompt {
public static final String prompt = System.getProperty("user.name")+">";
public static void main(String[] args) {
System.out.println(prompt);
}
}
Something like that should work. 这样的事情应该起作用。 See this tutorial for more information 有关更多信息,请参见本教程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.