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

时间:2015-05-06 15:10:18

标签: java loops user-input binary-search

我想从用户那里获取用户输入并进行非递归二进制搜索,任何人都可以告诉我该如何操作它将不胜感激

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();
}
}

2 个答案:

答案 0 :(得分:5)

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));
}

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

答案 1 :(得分:2)

根据我的理解,您希望在数组中搜索输入的值并返回其索引。

因此,您首先需要从用户输入中获取值,然后在数组中搜索它,如下所示:

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