public class binarysearch {
public static int search(num, 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;
}
}
}
public static void main(String[] args) {
binarysearch ob = new binarysearch();
int target_value = 69;
int[] num = {10,23,45,11,69,81};
int result = ob.search(num,target_value);
if (result == -1) {
System.out.println("Element not present");
} else {
System.out.println("Element is present" + mid);
}
}
}
谁能告诉我我到底做错了什么?我在执行代码时遇到编译错误。
我试图实现二进制搜索,我收到这个错误:
/binarysearch.java:2: error: <identifier> expected
public static int search(num,target_value)
^
/binarysearch.java:2: error: <identifier> expected
public static int search(num,target_value)
^
2 errors
必须在方法中添加类型参数
public static int search(int[] num, int target_value)
如果你把方法设为静态你就不需要声明对象
你可以直接调用方法
int result = search(num,target_value);
@Bahij。Mik在评论中提到,你遗漏了方法签名中的类型。因此将search
方法更改为:
public static int search(int[] num, int target_value) {
..
}
注意:还可以查看Java静态关键字指南!