//二分搜索
public class BinarySearch {
//Function of BinarySearch
//错误是BinarySearch方法导致的
int BinarySearch(int array[], int n, int num){
//if the result is not found,then return -1
int left = 0;
int right = n-1;
while(left <= right){
int middle = (left + right) / 2;
if (num == array[middle])
return middle;
else if(num > array[middle])
return middle + 1;
else
return middle - 1;
}
return -1;
}
public static void main(String args[]){
int array[]={1, 2, 3, 6, 7, 7, 8};
System.out.println(BinarySearch(array,7,7));
}
}
运行代码报错如下:
Cannot make a static reference to the non-static method BinarySearch(int[], int, int) from the type BinarySearch
先上错误代码:
原因如下:
非静态变量是依赖于对象存在的,对象必须实例化之后它的变量才会在内存中存在。
而静态成员不依赖于对象存在,即便是类所属的对象不存在也可以被访问。因为静态方法对于整个进程而言是全局的。
简言之:
在静态方法中,不能直接访问非静态成员(包括方法和变量)