显示java错误我想返回if(){}的值

qlvxas9a  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(229)

这是我的二进制搜索程序。我在寻找 Item=a[4]=5 . 如何从while循环中存在的if语句返回值,而不在循环外声明return语句。

package Array;

class myArray
{
    int a[]= {1,2,3,4,5,6,7,8,9,10};
    //this block is only for printing the array
    {
        for(int i=0; i<=9;i++)
        {
            System.out.println(a[i]);
        }
    }
    public int LocationFinder()
    {   
        int Start=a[0],End=a[9],Item=a[4],loc=0;
        while(Start<=End)
        {
            int mid=(Start+End)/2;
            if(Item==mid)
            {
            Item=loc;
            return loc; // <-- I want to return from here
            }
            else if(Item>mid)
            {
                Start=mid+1;
            }
            else
                End=mid-1;

        }

    }

我想从上面的位置返回,但是发生了一个错误。我怎样才能摆脱这个错误?

rkue9o1l

rkue9o1l1#

您的方法应如下所示:
使用索引:

public int LocationFinder()
    {   
          int Start=0,End=arr.length - 1,Item=a[4];
//Item = key 

while(Start<=End)
        {
            int mid=Start + (End-Start)/2;
            //Checking if item is present at mid     
            if(arr[mid]==Item)
            {
            return mid; //returning the index 
            }
            //if item is greater, than ignore the left side
            else if(arr[mid]<Item)
            {
                Start=mid+1;
            }
            //if item is smaller, than ignore the right side
            else
                End=mid-1;
 }
//returning -1 if the value is not found
return -1;
}

使用值:

public int LocationFinder()
            {   
          int Start=arr[0],End=arr[length - 1],Item=a[4];
//Item = key 

        while(Start<=End)
                {
                    int mid=(Start + End)/2;
                    //Checking if item is present at mid     
                    if(arr[mid]==Item)
                    {
                    return mid; //returning the index 
                    }
                    //if item is greater, than ignore the left side
                    else if(arr[mid]<Item)
                    {
                        Start=mid+1;
                    }
                    //if item is smaller, than ignore the right side
                    else
                        End=mid-1;
         }
        //returning -1 if the value is not found
        return -1;
        }

如需进一步帮助,请参阅以下内容:
二进制搜索

相关问题