我写了这个测试代码:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Run Code Online (Sandbox Code Playgroud)
但它给出了以下错误:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
Run Code Online (Sandbox Code Playgroud)
如何让我的方法识别我的类变量?
我试图在我的main createFile方法中从OpenFile类中调用我的方法,但我不断收到错误,说我不能从静态上下文中调用非静态变量.
我确实尝试OpenFile of = new OpenFile();在我的main方法中调用,但是这没有用,所以我现在声明OpenFile我的main方法上面工作正常,但是每次我尝试使用OpenFiles方法之一时我都会得到相同的错误.
我尝试过使用一些东西,static但这只会导致我的IDE显示错误的sym类型错误,我认为这是由引起其他错误的任何原因引起的.
这是createFile来自OpenFile:
public class OpenFile {
private Formatter file;
public void createFile() throws FileNotFoundException{
try{
file = new Formatter("test.txt");
} catch(Exception e) {
System.out.println("Error creating file.");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的主要方法:
OpenFile of = new OpenFile();
public static void main(String[] args) {
// TODO code application logic here
of.createFile();
intro();
createAndShowRibbon();
createAndShowNormalUI();
}
Run Code Online (Sandbox Code Playgroud)
它与Formatter有关吗?我以前从未使用过它.
谢谢.