[2017-03-04]Cannot make a static reference to the non-static method.....

//二分搜索
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

先上错误代码:



原因如下:
非静态变量是依赖于对象存在的,对象必须实例化之后它的变量才会在内存中存在。
而静态成员不依赖于对象存在,即便是类所属的对象不存在也可以被访问。因为静态方法对于整个进程而言是全局的。
简言之:
在静态方法中,不能直接访问非静态成员(包括方法和变量)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值