-3

可能重复:
初学者 Java - 静态错误

public class HelloWorld {
    public static void main(String [] args) {
        char[] b = {'a', 'b', 'a', 'c'};
        int p = 4;
        deleteRepeats(b, p);
    }

    public void deleteRepeats(char[] a, int size) {
        int currentElement;
        currentElement = 0;
        do {
            for (int i = currentElement; i < size-1; i++) {
                if (a[currentElement] == a[i+1]) a[i+1] = ' ';
            }
            currentElement++;
        } while (currentElement < size-1);
    }
}

我得到错误:

非静态方法 deleteRepeats(char[],int) 不能从静态上下文中引用 deleteRepeats(b,p);

有人能告诉我这是什么意思吗?

我尝试从主要方法中删除“静态”,但出现错误:

线程“main”中的异常 java.lang.NoSuchMethodError: main.

提前致谢

4

2 回答 2

0

您不能删除作为 java 标准方式的静态表单主方法。你可以删除它,那么它只是一种方法。您无法运行该程序。

与您交谈

 public void deleteRepeats(char[] a, int size) 

方法

1)您可以将其设为静态并在 main 方法中调用

 public static  void deleteRepeats(char[] a, int size) 

你现在的主要方法,

  public static void main(String [] args){
         char[] b = {'a', 'b', 'a', 'c'};
        int p=4;
        deleteRepeats(b,p);
    }   

2)否则您可以按原样使用deleteRepeats方法并通过创建一个对象来调用main方法,

这样

public static void main(String [] args){
   HelloWorld hello = new HelloWorld();
         char[] b = {'a', 'b', 'a', 'c'};
        int p=4;
        hello.deleteRepeats(b,p);
    }   
于 2012-11-01T04:57:08.143 回答
0

你需要做deleteRepeats一个类方法

//Note the "static"
public static void deleteRepeats(char[] a, int size) {
    //...
}

可以调用类方法,而无需调用它们的对象。没有声明的方法static称为实例方法,它们必须在对象上调用:

public class HelloWorld{
    private int instanceField = 10;
    private static int classField = 30;
    //Main is initially invoked without creating an object
    public static void main(String [] args){
        //So it is only possible to call methods that do not require an object,
        classMethodExample();
        //until an object is created...
        HelloWorld helloWorldObject = new HelloWorld();
        //at which point it becomes possible to call
        //member functions on that object
        helloWorldObject.instanceMethodExample();
        //Modify "helloWorldObject", and call instanceMethodExample again.
        helloWorldObject.instanceField = 20;
        helloWorldObject.instanceMethodExample();
    }
    public static void classMethodExample() {
        //Not invoked on an object, so cannot access instanceField
        //Can access classField
        System.out.println(classField); //prints "30"
    }

    public void instanceMethodExample() {
        //Can access instanceField within helloWorldObject
        System.out.println(instanceField); //prints "10" on the first call,
                                           //"20" on the second call
        //Can also access classField
        System.out.println(classField); //prints "30"
    }

}
于 2012-11-01T04:39:39.027 回答