person3122
person3122

Reputation: 31

How to get get rid of duplicate values in an int array?

The question is as the title says, how would I get rid of duplicate values in an integer array? I want to have it so the user inputs five numbers, all ranging between 10 and 100. The catch is that I have to have it so that if the value they are inputting has already been input into the array it will not count. Here is the code I have so far:

public static void main(String[]args){
    Scanner input = new Scanner(System.in);

    int[] intArray = new int[5]; //max of 5 values

    for(int i = 0; i < 5; i++){
        System.out.println("Please enter your desired number that is between 10 and 100: ");
            intArray[i] = input.nextInt(); //puts the value into the array
        }
    System.out.println(Arrays.toString(intArray)); //for test purposes to make sure the array was correctly taking in the values
    }
}


    System.out.println(Arrays.toString(intArray)); //for test purposes to make sure the array was correctly taking in the values

I am confused on how I would make it so if the user inputs a number that already exists in the array it will just not add it. Here is an example of what I mean, say the user inputs the numbers 15, 22, 46, 46, 77 once the program is done looping five times it will print out the following: [15, 22, 46, 77]. I am stuck on how to do this. Also I have edited out the if the number is between 10 and 100 if statements for it to be easier to read, and get to the main point at hand.

Upvotes: 2

Views: 978

Answers (5)

fps
fps

Reputation: 34460

A one liner would accomplish what you want:

Set<Integer> noDuplicates = new LinkedHashSet<>(Arrays.asList(intArray));

Do this after you read the values and store them in your intArray.

If you want to preserve the order in which the values were entered, use a LinkedHashSet, otherwise use just a HashSet.

A Set is a collection that cannot have duplicates.

Upvotes: 0

aa333
aa333

Reputation: 2576

If you just have to select unique numbers from the numbers that a user will input, don't store them in an Array initially.

Instead, store them in a HashMap/Hashtable and then once the user input is finished convert it to an Array.

Another way of doing this would be to use the Set Collection. Add each number you receive to an instance of the Set and finally convert the Set to an Array. Set will maintain uniqueness by default.

public static void main(String[]args){
    Scanner input = new Scanner(System.in);
    int[] intArray = new int[5]; //max of 5 values
    Set<Integer> uniques = new HashSet<Integer>();
    for(int i = 0; i < 5; i++){
        System.out.println("Please enter your desired number that is between 10 and 100: ");
        uniques.add(input.nextInt()); //puts the value in the set
    }
    System.out.println(Arrays.toString(uniques.toArray())); //for test purposes to make sure the array was correctly taking in the values
}

Upvotes: 0

Sergio0694
Sergio0694

Reputation: 4567

You're saying you want a variable number of numbers at the end, so an array is not the right choice here, use an ArrayList instead.

Something like:

List<Integer> intList = new ArrayList<Integer>();
int maxElements = 5; //Set max value here
for(int i = 0; i < maxElements ; i++)
{
    System.out.println("Please enter your desired number that is between 10 and 100: ");
    Integer newNumber = input.nextInt();
    if(newNumber  >= 10 && newNumber  <= 100)
    {
        Boolean found = false;
        foreach (Integer check : intList)
        {
            if (check == newNumber)
            {
                 found = true;
                 break;
            }
        }
        if (!found) intList.Add(newNumber);
    }
    else if(newNumber < 10 || newNumber > 100)
    {
        System.out.println("Enter a valid number next time, this number will not be counted in the results.");
    }
}

Duplicate check: that inner loop I added checks if there is another element with the same value, and in that case skips the number as you said.

I wrote this without a computer, so I could have mixed some stuff up, but you get the general idea.

Upvotes: 0

David Ehrmann
David Ehrmann

Reputation: 7576

What about using a Set? A LinkedHashSet, in particular, allows you to do this in O(n) time and memory, while retaining the order of the inputs. And before you say "But I can't use a HashSet," you'll need its behavior for the optimal solution, so the followup question might be "How would I implement a LinkedHashSet, possibly baking the logic into my program?"

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    Set<Integer> intSet = new LinkedHashSet<>();
    int[] intArray = new int[5]; //max of 5 values

    for (int i = 0; i < 5; i++) {
        System.out.println("Please enter your desired number that is between 10 and 100: ");
        intSet.add(input.nextInt());
    }

    int[] intArray = new int[intSet.size()];

    int i = 0;
    for (Integer val : intSet) {
        intArray[i++] = val;
    }
}

Upvotes: 2

minchang
minchang

Reputation: 9

  1. make your array size 100 and using input as a index. before update array[input] = input, check the value of the index (input number) of the array.

  2. use a map store input values as a key. before save the value in array, check whether key is in a map or not.

Upvotes: -1

Related Questions