如何在上面的代码中添加用户输入

How to add user input above code

我想从用户那里获取用户输入并进行非递归二进制搜索,谁能告诉我怎么做,我将不胜感激

public class Main {
// binarySeach: non-recursive
   public int Main(int[] a, int x) {
      int low = 0;
  int high = a.length - 1;
  while (low <= high) {
     int mid = (low + high)/2;
     if (a[mid] == x) return mid;
     else if (a[mid] < x) low = mid + 1;
     else high = mid - 1;
  }
  return -1;
  }



 public static void main(String[] args) {
      Main bin = new Main();
  int[] a =
    { 2, 8,12,14,16,19,24,28,31,33,// 0-9
     39,40,45,49,51,53,54,56,57,60,// 10-19
     63,69,77,82,88,89,94,96,97};  // 20-28
  for (int i = 0; i < a.length; i++)
     System.out.print(bin.Main(a,
        a[i]) + " ");   

  System.out.println();
}
}
public static void main(String[] args) {
    Main bin = new Main();
    int[] a = { 2, 8,12,14,16,19,24,28,31,33,// 0-9
                39,40,45,49,51,53,54,56,57,60,// 10-19
                63,69,77,82,88,89,94,96,97};  // 20-28
    Scanner userinput = new Scanner(System.in);
    System.out.println("Enter number to search");
    int n = userinput.nextInt();
    System.out.println("Number index: "+bin.Main(a, n));
}

首先注意 position/index 是 0,所以如果你想得到数字 12 的数字索引 3 而不是索引 2,将 System.out.println("Number index: "+bin.Main(a, n)); 更改为 System.out.println("Number index: "(bin.Main(a, n)+1));

据我了解,您想在数组中搜索输入的值及其索引 return。

所以您首先需要从用户输入中获取值,然后像这样在您的数组中搜索它:

public class Main {
     public int Search(int[] a, int x) {
         int low = 0;
         int high = a.length - 1;
         Boolean search=false;
         while (low <= high && !search) {
            int mid = (low + high)/2;
            if (a[mid] == x) {
                search=true;
                return mid;
            }
            else if (a[mid] < x) low = mid + 1;
            else high = mid - 1;
         }
         return -1;
     }


     public static void main(String[] args) {
          Main bin = new Main();
          int[] a ={ 2, 8,12,14,16,19,24,28,31,33,// 0-9
             39,40,45,49,51,53,54,56,57,60,// 10-19
             63,69,77,82,88,89,94,96,97};  // 20-28
          Scanner input = new Scanner(System.in);
          System.out.println("Enter the number you whould like to search !");
             int n=input.nextInt();
             int index=bin.Search(a,n);
             if(index<0) { //-1 means that the element doesn't exist in the array 
                System.out.println("This number doesn't exist in the array "); 
             } else { //The "}" before the else was missing
                System.out.println("The index of the number "+n+" in the array is :"+ index);
             }

     }
}

你需要使用 Scanner 来获取用户输入,你不需要循环数组来搜索它,你只需要调用你的搜索方法并传递 arrayinputted value 作为参数。

编辑:

看直播DEMO here,输入是8,ineex是1