You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java二分查找代码编译错误求助:<identifier> expected报错

Java二分查找代码编译错误排查及修复

编译报错的直接原因

你遇到的<identifier> expected错误,核心原因是Java作为强类型语言,方法参数必须显式声明类型。原代码中search(num, target_value)没有指定参数类型,编译器无法识别参数的类型信息,必须修改为:

public static int search(int[] num, int target_value)

其他必须修复的问题

除了编译错误,代码还有几个逻辑和语法问题,不修复的话即使编译通过也无法正常运行:

  • 静态方法无需实例化调用:search是静态方法,直接通过类名调用即可,不需要创建binarysearch对象,把ob.search(num,target_value)改成binarysearch.search(num,target_value)。
  • 方法缺少默认返回值:search声明返回int类型,但while循环结束后没有返回语句,当循环结束还没找到目标值时,需要返回-1表示元素不存在。
  • 二分查找依赖有序数组:当前传入的数组{10,23,45,11,69,81}是无序的,二分查找的逻辑完全基于有序数组,必须先排序,比如调整为{10,11,23,45,69,81}。
  • 引用未定义变量:main方法里的System.out.println("Element is present" + mid),mid是search方法的局部变量,main方法无法访问,应该用接收结果的result代替。
  • 循环条件遗漏边界:原代码while (low < high)会遗漏最后一个元素的判断,应该改成while (low <= high)。

修复后的完整代码

public class binarysearch {
    public static int search(int[] num, int target_value) {
        int low = 0;
        int mid;
        int high = num.length - 1;
        
        while (low <= high) {
            mid = (low + high) / 2;

            if (num[mid] == target_value) {
                return mid;
            }

            if (num[mid] < target_value){
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1; // 未找到元素时返回-1
    }

    public static void main(String[] args) {
        int target_value = 69;
        // 排序后的数组
        int[] num = {10,11,23,45,69,81};
        int result = binarysearch.search(num,target_value);
        
        if (result == -1) {
          System.out.println("Element not present");
        } else {
          System.out.println("Element is present at index: " + result);
        }
    }
}

内容的提问来源于stack exchange,提问作者Jack Sparrow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:55:26