Cannot find symbol Java error?

ⅰ亾dé卋堺 提交于 2019-12-04 00:59:59

问题


The code works when I used java.util.Arrays.sort(numbers); Am I doing something wrong? This seems weird to me.

import java.util.Arrays.*;

class Test {
   public static void main(String[] args) {
    double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};
    char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};

    sort(numbers);

    System.out.println(binarySearch(numbers, 3));

   }
}

(Error displayed in terminal)

Test.java:8: error: cannot find symbol
    sort(numbers);
    ^
symbol:   method sort(double[])
location: class Test
 Test.java:10: error: cannot find symbol
    System.out.println(binarySearch(numbers, 3));
                       ^
 symbol:   method binarySearch(double[],int)
 location: class Test
  2 errors

回答1:


It's a static method of the class Arrays.

You should invoke it like this:

Arrays.sort(someArray);

Note you still have to import the Arrays class like this:

import java.util.Arrays;

Or as others have mentioned, if you do a static import you can omit the class name.

I would argue that Arrays.sort() is better for readability.




回答2:


you need to do a static import. Use the following

import static java.util.Arrays.*;

Reason

when you want to import some static members (methods or variables), you need to static import the members. So you have to use import static

Another solution

or you can import

import java.util.Arrays;

and use

Arrays.sort(b);

Reason of the second Solution

here you are not importing any static elements so normal import to Arrays is needed. Then you can directly access using Arrays.sort




回答3:


You are attempting to do a static import, but you missed static.

//   add v this
import static java.util.Arrays.*;


来源:https://stackoverflow.com/questions/16742270/cannot-find-symbol-java-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!