【发布时间】:2015-02-19 03:37:32
【问题描述】:
这是我的代码。我找不到问题。请帮我。我在 Eclipse 中有这个错误:
令牌语法错误,结构错位
在递归方法的行旁边写着错误
if (arr[mid] == item) {
但在我看来,我所有的大括号和构造函数都很好,一切都很好。我在构造函数上也有一个错误,上面写着:
缺少方法返回类型。
我认为构造函数不应该有返回类型,对吧?
public final class IntegerBinSearch {
/**
* Default constructor.
*/
private IntegerBinarySearch() {
}
/**
* Returns the index of the item that you are looking for, -1
* if the item isn't in the array.
* The array must be sorted.
*
* @param array the array that will be searched.
* @param item the item that the method will try to find.
* @return the index of the item's location, returns -1 if not found.
*/
public static int binarySearch(Integer[] array, int item) {
int high = array.length - 1;
int low = 0;
int mid = (high + low) / 2;
for (int i = array.length; i > 0; i /= 2) {
if (array[mid] == item) {
return mid;
} else if (array[mid] > item) {
high = mid - 1;
mid = (high + low) / 2;
} else {
low = mid + 1;
mid = (high + low) / 2;
}
}
return -1;
}
/**
* Returns the index of the location of the given item, else returns -1.
*
* @param array array of Integers that will be searched.
* @param item item that will be searched for.
* @param low lower bound of the array's contents to search.
* @param high upper bound of the array's contents to search.
* @return returns the index of the location of the given item, returns -1 if item is not found.
*/
public static int binarySearchRecursive(Integer[] arr, int item, int low, int high) {
int mid = (high + low) / 2;
if (arr[mid] == item) {
return mid;
}
else(arr[mid] > item) {
return binarySearchRecursive(arr, item, low, mid - 1);
} else {
return binarySearchRecursive(arr, item, mid + 1, high);
}
}
}
【问题讨论】:
-
构造函数错误是因为你的类名为IntegerBinSearch,但你的构造函数名为IntegerBinarySearch(啊,错别字!)。另外,
else (array[mid] > item)的错误是因为您缺少单词if
标签: java eclipse recursion compiler-errors binary-search