英文:
How to prevent duplicates in array?
问题
我正在尝试创建一个程序,您不能使用已经被占用的相同ID添加新员工。但是,使用这段代码仍然会添加员工。您有什么建议,我如何更改我的代码?
另外,数组最多可以容纳10名员工。
如果需要,我将乐意提供更多信息。
for(Employee employee:employeeArray){
if(employee!= null && employee.getEmployeeID()。equals(eID)){
counter = employeeArray.length - 1;
System.out.println("您的集合中已经有ID为" + eID + "的员工");
} else if(counter < 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 && employee.getEmployeeID().equals(eID)) {
counter = employeeArray.length - 1;
System.out.println("An employee with " + eID + " is already in your collection");
} else if (counter < 10) {
employeeArray
= e_obj;0+网站访问量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 && 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 && employe.getEmployeID() != null && employe.getEmployeID().equals(eID)) {
isExisting = true;
break;
}
}
if(!isExisting) {
// Your existing logic to add the employee
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论