【问题标题】:Syntax error on token(s), misplaced construct(s) - Error in binary search methods标记上的语法错误,错误的构造 - 二进制搜索方法中的错误
【发布时间】: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


【解决方案1】:

当你使用多个条件时,你应该写 else if 语句

你应该替换

else (arr[mid] > item) {

else if (arr[mid] > item) {

并且构造函数名称必须与@Adam所说的类名相同

请尝试

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多