首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

大神帮小弟我看看这个小的查找,哪里出错了

2012-03-16 
大神帮我看看这个小的查找,哪里出错了?public class Search{public static void main(String [] args) {in

大神帮我看看这个小的查找,哪里出错了?
public class Search{
public static void main(String [] args) {
int a[] = {1, 3, 4, 7, 9, 20, 58, 79 };
int i = 9;
System.out.println(twofen(a,i));

}
public static int twofen(int []a,int num) {
if(a.length == 0)return -1;
int firstpos = 0;
int lastpos = a.length -1;
int m = (firstpos + lastpos) / 2;
while(firstpos <= lastpos){
if(num == a[m])return m;
if(num < a[m]){lastpos = a[m]-1;}
if(num > a[m]){firstpos = a[m]+1;}
m = (firstpos + lastpos) / 2;
}
return -1;
}

[解决办法]
你明显那个部分if没有返回值
while(firstpos <= lastpos){
if(num == a[m])return m;
if(num < a[m]){lastpos = (m-1)/2;}
if(num > a[m]){firstpos = (m+1)/2;}
m = (firstpos + lastpos) / 2;
return -1;
}
修改成
while(firstpos <= lastpos){
if(num == a[m])return m;
if(num < a[m]){lastpos = (m-1)/2;}
if(num > a[m]){firstpos = (m+1)/2;}
m = (firstpos + lastpos) / 2;
return m;}
}
return -1;
}

[解决办法]
刚才那个有点小错误,重发个:

Java code
public class Search{public static void main(String [] args) {int a[] = {1, 3, 4, 7, 9, 20, 58, 79 };int i = -1;System.out.println(twofen(a,i));}  public static int twofen(int []a,int num) {if(a.length == 0)return -1;int firstpos = 0;int lastpos = a.length -1;while(firstpos <=lastpos){if(num == a[(firstpos + lastpos) / 2])return (firstpos + lastpos) / 2;if(num < a[(firstpos + lastpos) / 2]){lastpos = ((firstpos + lastpos) / 2)-1;}if(num > a[(firstpos + lastpos) / 2]){firstpos = ((firstpos + lastpos) / 2)+1;}}return -1;}}
[解决办法]
将if(num < a[m]){
lastpos = a[m]-1;
}
if(num > a[m]){
firstpos = a[m]+1;
}两名改为:
if(num < a[m]){
lastpos = m-1;
}
if(num > a[m]){
firstpos = m+1;
}


[解决办法]
还有你好像多了一个大括号
[解决办法]
1,“int twofen(int []a,int num)”应将此函数应放在class Search里,而不是外面
2,“if(num < a[m]){lastpos = a[m]-1;}”须将 a[m]-1改为m-1
及“if(num > a[m]){firstpos = a[m]+1;}“里的a[m]+1改为m+1即可
[解决办法]
Java code
public class Search{    public static void main(String [] args) {        int a[] = {1, 3, 4, 7, 9, 20, 58, 79 };        int i = 9;        System.out.println(twofen(a,i));    }      public static int twofen(int []a,int num) {        if(a.length == 0) return -1;        int firstpos = 0;        int lastpos = a.length -1;        int m = (firstpos + lastpos) / 2;        while(firstpos <= lastpos){            if(num == a[m]) return m;            if(num < a[m]){    lastpos = m-1;}            if(num > a[m]){    firstpos = m+1;}            m = (firstpos + lastpos) / 2;        }        return -1;    }} 

热点排行