使数组中的所有值唯一

我正在做一个小型学校项目,请记住我是一个初学者。我要制作一个小型系统,将健身房的成员人数增加到一个数组中。我需要确保人们不能获得相同的会员号,换句话说,要确保在服务器索引点上不会出现相同的值。

到目前为止,我的方法如下:

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;
    } 
}

虽然有构造函数和一些类似这样的属性:

int[] memberNr; 
int arraySize;
int count; 

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

如您所见,我尝试使用equals,这似乎不起作用。。但是说实话,我不知道如何使每个值唯一 我希望你们中的一些可以帮助我 非常感谢

llk4j 回答:使数组中的所有值唯一

您可以在set中使用java

Set是扩展Collection的接口。它是对象的无序集合,无法存储重复的值。

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); 
    } 
} 
,
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;
}

我希望内联添加的注释可以解释代码。让我知道这是怎么回事。

,

嘿,您不能直接比较数组(一个整数值的集合) 首先迭代membernr中的元素,然后检查整数值

本文链接:https://www.f2er.com/3045201.html

大家都在问