Thor Christensen
Thor Christensen

Reputation: 83

Making all values in an array unique

Im making a small school project, keep in mind i'm a beginner. Im gonna make a small system that adds member numbers of members at a gym to an array. I need to make sure that people cant get the same member number, in other words make sure the same value doesnt appear on serveral index spots.

So far my method looks like this:

public void members(int mNr){
    if(arraySize < memberNr.length){
        throw new IllegalArgumentException("There are no more spots available");
    } 
    if(memberNr.equals(mNr)){
        throw new IllegalArgumentException("The member is already in the system");
    }
    else{
        memberNr[count++] = mNr;
    } 
}

While having a contructor and some attributes like this:

int[] memberNr; 
int arraySize;
int count; 

public TrainingList(int arraySize){
    this.arraySize = arraySize;
    this.memberNr = new int[arraySize];
}

As you can see i tried using equals, which doesnt seem to work.. But honestly i have no idea how to make each value unique I hope some of you can help me out Thanks alot

Upvotes: 1

Views: 80

Answers (3)

xavi4_4_4
xavi4_4_4

Reputation: 78

public void members(int mNr){
    if(arraySize < memberNr.length){
        throw new IllegalArgumentException("There are no more spots available");
    } 
    //You need to loop through your array and throw exception if the incoming value mNr already present
    for(int i=0; i<memberNr.length; i++){
       if(memberNr[i] == mNr){
         throw new IllegalArgumentException("The member is already in the system");
        }
     }
    //Otherwise just add it
     memberNr[count++] = mNr;
}

I hope the comments added inline explains the code. Let me know how this goes.

Upvotes: 2

arun
arun

Reputation: 26

Hey you can’t directly comparing arrays (collection of values with one integer value) First iterate the element in membernr and check with the integer value

Upvotes: 0

ali sarkhosh
ali sarkhosh

Reputation: 193

You can use set in java

Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.

mport java.util.*; 
public class Set_example 
{ 
    public static void main(String[] args) 
    { 
        // Set deonstration using HashSet 
        Set<String> hash_Set = new HashSet<String>(); 
        hash_Set.add("a"); 
        hash_Set.add("b"); 
        hash_Set.add("a"); 
        hash_Set.add("c"); 
        hash_Set.add("d"); 
        System.out.print("Set output without the duplicates"); 

        System.out.println(hash_Set); 

        // Set deonstration using TreeSet 
        System.out.print("Sorted Set after passing into TreeSet"); 
        Set<String> tree_Set = new TreeSet<String>(hash_Set); 
        System.out.println(tree_Set); 
    } 
} 

Upvotes: 3

Related Questions