我正在尝试编写代码,当您输入整数时,它会找到它所在的索引。问题是我要返回负数。我知道它是否找不到返回(-(插入点)-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);
}
}
得到-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
的内容进行排序之前将其打印出来。假定