我收到错误但我不明白如何解决它。 #BinarySearch

时间:2016-10-18 21:52:12

标签: java arrays

好的,所以我收到了这个错误:

BinarySearch.java:26: error: incompatible types: double cannot be converted to Integer
        Integer [] a = {-3,10,5,24,45.3,10.5};
                                   ^
BinarySearch.java:26: error: incompatible types: double cannot be converted to Integer
        Integer [] a = {-3,10,5,24,45.3,10.5};
                                        ^
BinarySearch.java:27: error: incompatible types: possible lossy conversion from double to int
        System.out.println("45.3 found at " +binarySearch( a, 45.3 ));
                                                          ^

我明白它告诉我的是什么,但我不知道如何解决它。我到处寻找修复但其他一切似乎都不合适。任何帮助都会很棒。这是我到目前为止的代码:

public class BinarySearch
{
    public static final int NOT_FOUND = -1;
    public int binarySearch( Integer [] a, int x )
    {
        int low = 0;
        int high = a.length - 1;
        int mid;
        while( low <= high )
        {
            mid = ( low + high ) / 2;

            if (a[mid].compareTo(x)<0)
                low = mid + 1;
            else if (a[mid].compareTo(x) > 0)
                high = mid - 1;
            else
                return mid;
        }
        return NOT_FOUND;
    }

    public static void main(String[] args)
    {
        int SIZE = 6;
        Integer [] a = {-3,10,5,24,45.3,10.5};
        System.out.println("45.3 found at " +binarySearch( a, 45.3 ));
    }
}

2 个答案:

答案 0 :(得分:1)

未订购数组。二进制搜索仅在排序数组时有效。

答案 1 :(得分:0)

您不能在Integer类型的数组中存储Double或Float类型的值(例如10.5) -

  

整数[] a = { - 3,10,5,24,45.3,10.5};

它应该被声明为Double类型的数组:

Double [] a = {-3, 10, 5, 24, 45.3, 10.5};

&安培;

  

public int binarySearch(Integer [] a,int x)

方法binarySearch()需要能够接受Double类型的数组,以及相同类型的可搜索值:

public int binarySearch(Double[] a, double x)