在Java中,为什么返回负数? [处于保留状态]

问题描述 投票:-8回答:1

我正在尝试编写代码,当您输入整数时,它会找到它所在的索引。问题是我要返回负数。我知道它是否找不到返回(-(插入点)-1)的索引。但是我检查了是否重复。我该如何解决?

public static void main(String[] args) {
    int [] ref = new int[10];
    Random rand = new Random();
    Scanner s = new Scanner(System.in);
    int i;
    int input = 1,index;
    ref[0] = rand.nextInt(10)+1;

    for(i=1 ; i<ref.length ; i++) { //check it is repeated or not
        do {
            ref[i] = rand.nextInt(10)+1;                
        }while(ref[i] == ref[i-1]);
    }

    Arrays.sort(ref);

    while(input!=0) {
        System.out.print("Put an integer (range: 1~10, 0 to quit): ");
        input = s.nextInt();
        index = Arrays.binarySearch(ref, input);
        System.out.println("index: " +index);
    }
}
java binary-search
1个回答
0
投票

得到-1的原因是:

    ref[0] = rand.nextInt(10) + 1;

    for (i = 1; i < ref.length; i++) { //check it is repeated or not
        do {
            ref[i] = rand.nextInt(10) + 1;              
        } while (ref[i] == ref[i - 1]);
    }

不执行您认为的操作。

您正在尝试用1到10之间的随机数填充ref,并且不能重复。但是,您检查重复的数字是不正确的。您需要对照[[全部 ref[i]ref[0]ref[i - 1]进行检查。

仍然。由于数字可能不是唯一的,因此1 .. 10中的某些数字可能会丢失。如果您搜索这些数字之一,则会得到-1


那么您怎么会自己发现这个问题?

    一种方法是在对ref的内容进行排序之前将其打印出来。
  • 另一种方法是使用调试器和单步执行或断点来观察代码在做什么,并检查变量。
  • 第三种方式是Rubber Duck debugging。 (严重)。

  • 最后,在调试应用程序时,

    假定

  • 所编写的代码正确是不明智的。看来您的思考过程是这样的:
      数组元素是唯一的,因为我用唯一值填充数组的代码是正确的。
    1. 我已经对数组进行了排序。
    2. 二进制搜索失败。
    3. 因此,排序方法或二进制搜索方法必须不正确。
  • 现在,库方法可能不正确。但是,这样做的机会通常很小,而且对于Java SE库方法来说是微不足道的,其他Java程序的“数百万”可能已经使用了Java SE库方法。
  • © www.soinside.com 2019 - 2024. All rights reserved.