静态引用错误

时间:2012-11-01 04:38:24

标签: java

  

可能重复:
  Beginner Java - Static Error

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方法中删除“static”,但是我收到错误:

  

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

提前致谢

2 个答案:

答案 0 :(得分: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"
    }

}

答案 1 :(得分:0)

你无法删除静态表单main方法,这是java标准方式。你可以删除它然后它只是一种方法。你无法运行这个程序。

与您交谈

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

方法

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

 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);
    }