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

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

How to prevent duplicates in array?

问题

  1. 我正在尝试创建一个程序您不能使用已经被占用的相同ID添加新员工但是使用这段代码仍然会添加员工您有什么建议我如何更改我的代码
  2. 另外数组最多可以容纳10名员工
  3. 如果需要我将乐意提供更多信息
  4. forEmployee employeeemployeeArray{
  5. ifemployee= null && employee.getEmployeeID()。equalseID)){
  6. counter = employeeArray.length - 1;
  7. System.out.println"您的集合中已经有ID为" + eID + "的员工";
  8. } else ifcounter < 10{
  9. employeeArray [counter] = e_obj;
  10. counter ++;
  11. }
  12. }
英文:

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.

  1. for (Employee employee : employeeArray) {
  2. if (employee != null &amp;&amp; employee.getEmployeeID().equals(eID)) {
  3. counter = employeeArray.length - 1;
  4. System.out.println(&quot;An employee with &quot; + eID + &quot; is already in your collection&quot;);
  5. } else if (counter &lt; 10) {
  6. employeeArray
    0
    +
    网站访问量
    = e_obj;
  7. counter++;
  8. }
  9. }

答案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 进行比较,我建议查看是否存在额外的空格或大小写敏感的问题。

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

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

  1. 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.

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

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

  1. counter = employeeArray.length - 1;

答案3

得分: 0

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

  1. // 检查员工是否已存在
  2. boolean isExisting = false;
  3. for (Employe employe : employeArr) {
  4. if (employe != null && employe.getEmployeID() != null && employe.getEmployeID().equals(eID)) {
  5. isExisting = true;
  6. break;
  7. }
  8. }
  9. if (!isExisting) {
  10. // 添加员工的现有逻辑
  11. }
英文:

You can do it as follows:

  1. // Check if the employee already exists
  2. boolean isExisting = false;
  3. for (Employe employe : employeArr) {
  4. if (employe != null &amp;&amp; employe.getEmployeID() != null &amp;&amp; employe.getEmployeID().equals(eID)) {
  5. isExisting = true;
  6. break;
  7. }
  8. }
  9. if(!isExisting) {
  10. // Your existing logic to add the employee
  11. }

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:

确定