我做错了什么?静态错误[Java]

时间:2013-04-09 21:38:48

标签: java static

它引用了一个错误,当我使用我的函数generatecode()时,我无法使用静态。我想看看我是否正确地进行了拆分。我是新人,仍需要一些帮助。在这种情况下,我已经看到了创建新类的一些事情:TestFile variable = new TestFile();我不知道这意味着什么。谢谢!

    public class TestFile {

String[] preps = {
    "about", "above", "across", "after", "against",
    "along", "among", "around", "at", "before",
    "behind", "below", "beneath", "beside", "between",
    "by", "concerning", "down", "during", "except",
    "for", "from", "in", "inside", "into",
    "like", "near", "of", "onto", "out",
    "over", "through", "to", "toward", "under",
    "up", "upon", "with", "within", "without"
};

String[] errorpreps = {
    "will", "would", "shall", "should", "can",
    "could", "may", "might", "must", 
};

String[] question = {
};

public static void main(String[] args) {

    generatecode("hi");

};

public generatecode(String code){

    String prep = "";

    for (int i=0; i<preps.length; i++){

        prep = prep + preps[i];

    }

    System.out.println(prep);

    return prep;

}

public String printcode(String code){


    return "";

}

    }

3 个答案:

答案 0 :(得分:1)

您的方法有错误的访问修饰符:

public generatecode(String code){

应该是

public static String generatecode(String code){

请注意

你也没有这个方法的返回类型,所以这真的不应该编译。

为什么会这样?

当没有对象实例时,可以运行像main(String[] args)这样的静态方法。所以你可以打电话:

ClassName.method();

当您尝试从静态方法调用实例方法时,这意味着您尝试使用需要对象实例存在的代码功能。所以回顾一下:

ClassName c = new ClassName();
c.instanceMethod(); // This is an instance method.

ClassName.staticMethod(); // This is a static method.

答案 1 :(得分:1)

static main方法中,您尚未拥有TestFile课程的任何实例。要引用非static的任何内容,您需要该类的实例。这正是TestFile variable = new TestFile();行的作用 - 它创建了TestFile的新实例。

然后你可以在你的实例上调用你的方法:

variable.generatecode("hi");

正如@ChrisCooney已经指出的那样,你没有该方法的返回类型。所有方法都需要返回类型。在这种情况下,您需要声明您的方法返回String,因为这是方法返回的内容。

答案 2 :(得分:0)

generate是一种实例方法,您尝试从main调用它,这是一种静态方法。要解决它,你可以这样做.-

(new TestFile()).generatecode("hi");

相关问题