2015-03-31 50 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); 

} 

}