如何防止数组中的重复项?

huangapple go评论136阅读模式
英文:

How to prevent duplicates in array?

问题

我正在尝试创建一个程序您不能使用已经被占用的相同ID添加新员工但是使用这段代码仍然会添加员工您有什么建议我如何更改我的代码

另外数组最多可以容纳10名员工

如果需要我将乐意提供更多信息

forEmployee employeeemployeeArray{
    ifemployee= null && employee.getEmployeeID()。equalseID)){
        counter = employeeArray.length  - 1;
        System.out.println"您的集合中已经有ID为" + eID + "的员工";

    } else ifcounter < 10{
        employeeArray [counter] = e_obj;
        counter ++;
    }
}
英文:

I'm trying to make a program where you can't add a new employee with the same ID that is already taken. But with this code it adds the employee anyways. Any suggestions to how I can change my code?

Also the array is supposed to hold a maximum of 10 employees.

I´ll gladly provide any more information if needed.

for (Employee employee : employeeArray) {
    if (employee != null &amp;&amp; employee.getEmployeeID().equals(eID)) {
        counter = employeeArray.length - 1;
        System.out.println(&quot;An employee with &quot; + eID + &quot; is already in your collection&quot;);

    } else if (counter &lt; 10) {
        employeeArray
0
+
网站访问量
= e_obj; counter++; } }

答案1

得分: 2

使用HashSet替代这个。只需创建一个HashSet或者集合(set)的对象,它将不会接受任何重复的值。

英文:

Use HashSet instead of this. just create an object of HashSet or set and it will not accept any duplicate values from you.

答案2

得分: 1

如果 getEmployeeID 返回一个字符串并将其与字符串 eID 进行比较,我建议查看是否存在额外的空格或大小写敏感的问题。

if (employee != null && employee.getEmployeeID().equals(eID)) {

另外,您不需要在 if 语句中调整计数器。

counter = employeeArray.length - 1;
英文:

If getEmployeeID returns a String and compares it to a String eID I suggest seeing if there might be extra white space or a case sensitivity issue.

if (employee != null &amp;&amp; employee.getEmployeeID().equals(eID)) {

Also, you shouldn't need to adjust the counter in the if clause.

counter = employeeArray.length - 1;

答案3

得分: 0

你可以按照以下方式操作:

// 检查员工是否已存在

boolean isExisting = false;

for (Employe employe : employeArr) {
    if (employe != null && employe.getEmployeID() != null && employe.getEmployeID().equals(eID)) {
        isExisting = true;
        break;
    }
}

if (!isExisting) {
    // 添加员工的现有逻辑
}
英文:

You can do it as follows:

// Check if the employee already exists

boolean isExisting = false;

for (Employe employe : employeArr) {
	if (employe != null &amp;&amp; employe.getEmployeID() != null &amp;&amp; employe.getEmployeID().equals(eID)) {
		isExisting = true;
		break;
	}
}

if(!isExisting) {
	// Your existing logic to add the employee
}

huangapple
  • 本文由 发表于 2020年9月6日 18:53:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63763310.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定