Java 我收到一个错误,但我没有';我不知道如何修理它#二进制搜索
好的,我收到了这个错误:Java 我收到一个错误,但我没有';我不知道如何修理它#二进制搜索,java,arrays,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
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 ));
}
}
公共类二进制搜索
{
公共静态final int NOT_FOUND=-1;
公共整数二进制搜索(整数[]a,整数x)
{
int低=0;
int高=a.长度-1;
int mid;
while(low数组未排序。只有当数组排序时,二进制搜索才起作用。不能在整型数组中存储Double或Float(例如10.5)类型的值--
整数[]a={-3,10,5,24,45.3,10.5}
它应该声明为Double类型的数组:
Double [] a = {-3, 10, 5, 24, 45.3, 10.5};
&
公共整数二进制搜索(整数[]a,整数x)
方法binarySearch()需要能够接受Double类型的数组和相同类型的可搜索值:
public int binarySearch(Double[] a, double x)
错误信息非常具体:double不能转换为整数。你有一个数组,你说它保存整数,但你把浮点数放在ot中。将10.5
更改为10
或11
和45.3
更改为45
或46
。int
不是一个整数值和一个整数位。@ElliottFrisch我不允许更改数字,它们必须保持原样。然后将Integer
更改为Double
。您必须确保在其他地方也进行了所有必需的更改,如方法参数。