我正在开发一个程序,它将获取用户输入,然后将其存储在一个数组中。然后,它将搜索数组以查看用户输入的数字是否重复。由于某些原因,binarySearch没有检测到重复。
我的代码是:
import java.util.Arrays;
import java.util.Scanner;
public class Duplicate_Elimination
{
public static void main(String[] args)
{
int [] numbers = new int[5]; // create an array
Scanner input = new Scanner(System.in); // create a Scanner
// Ask user for 5 numbers
for (int i = 0; i < 5; i++)
{
// ask user to type the number
System.out.printf("Please type number %d:",i+1);
int number = input.nextInt(); // get user input and store it in number variable
// check if the number entered is already stored
int location = Arrays.binarySearch(numbers,number);
// store the value inside number variable in numbers array
numbers[i] = number;
showArray(numbers);
// if there is any similarity between numbers, print error message
if (location >= 0)
System.out.printf("%s%n","error");
} // end for
}
// this method will show what's in the array
public static void showArray(int[] numbers)
{
System.out.printf("%n%n"); // print black spaces
// print all the numbers stored in the array
for(int digit: numbers)
{
System.out.printf("%d",digit);
}
System.out.printf("%n"); // print black space
}
}
我尽力解决,但是当我输入1作为我的所有数字时,它只会在键入3个数字后显示重复。它应该在每次输入后检测到重复。能否请你帮我弄清楚我的代码有什么问题。我真的很感激。
谢谢!
答案 0 :(得分:3)
来自java.util.Arrays documentation:
public static int binarySearch(int [] a, int key)
使用二进制搜索算法在指定的int数组中搜索指定的值。数组必须是 在进行此调用之前,排序(通过sort(int [])方法)。如果它 未排序,结果未定义。
所以你需要在每次插入后对数组进行排序。
答案 1 :(得分:0)
从我所看到的情况来看,我认为通过评论来消除相似性应该有效。
showArray(numbers);
// if there is any similarity between numbers, print error message
//if (location >= 0)
//System.out.printf("%s%n","error");
} // end for
}