[Solved] Array that takes user input to fill but does not allow duplicate elements


You should look into a collection called Set. There is a pretty handy function Set.contains that will return true or false depending if a number is already in the Set or not. Something like this would do the trick:

Scanner scanner = new Scanner(System.in);
int maxNum = 8;
Set<Integer> numbers = new HashSet<>();
int digCounter = 1;

//Run while we need numbers
while (digCounter <= maxNum) {
    System.out.println("Enter digit " + digCounter + ":");
    int tempNumber = scanner.nextInt();
    if (numbers.contains(tempNumber)) { //If number is already chosen
        System.out.println("Sorry that number has already been added");
    } else { //If new number
        digCounter++;
        numbers.add(tempNumber);
    }
}
System.out.println(numbers);

Or if you HAVE to use only arrays you can do something like this:

Scanner scanner = new Scanner(System.in);
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicate;
int digCounter = 1;

// Run while we need numbers
while (digCounter <= maxNum) {
    //reset duplicate
    duplicate = false;
    //Get user input
    System.out.println("Enter digit " + digCounter + ":");
    int temp = scanner.nextInt();
    for (int i = 0; i <= digCounter - 2; i++) { //Loop through accepted numbers
        if (temp == arrayIn[i]) { //We have found a match
            duplicate = true;
            break;
        }
    }
    //Check if duplicate
    if (duplicate) {
        System.out.println("Sorry that number has already been added");
    } else {
        arrayIn[digCounter - 1] = temp;
        digCounter++;
    }
}
System.out.println(Arrays.toString(arrayIn));

Hope this helps!

3

solved Array that takes user input to fill but does not allow duplicate elements