【问题标题】:How to error handle duplicate student ID in array如何错误处理数组中重复的学生 ID
【发布时间】:2020-02-08 07:14:28
【问题描述】:

请帮助我了解如何防止在 ID 重复的情况下插入学生。我试图了解如何不导入任何东西,但我不介意你分享你得到的任何东西,这样我就可以学习了。谢谢

我尝试遍历每个对象并检查 studentArray.getID() 是否匹配,但我似乎无法正确输出。我还尝试将每个 ID 存储到另一个数组中并比较两个数组,尽管我认为我必须使用嵌套的 for 循环并且它破坏了我的所有代码。我也无法弄清楚如何将 ID 设置为 1,然后将 1 添加到最大值 10,因为 studentArray[10] 是 10。所以这段代码是我能提供的最干净的代码。

int size = studentArray.length;
System.out.print("Insert Student ID: ");
int ID = sc.nextInt();
System.out.print("Insert Student Name: ");
String name = sc.next();
System.out.print("Insert Student Age: ");
int age = sc.nextInt();
Student student1 = new Student(name,age,ID);
studentArray[size] = student1;
size++;
System.out.print("\nStudent Inserted!\n");

【问题讨论】:

  • 为什么不使用Set 来避免重复元素?
  • 不确定我是否理解
  • 接口java.util.Set请参考javadoc
  • "Student 类型不是通用的。它不能用参数参数化 " 我不应该使用任何集合
  • 如果您不想使用任何集合,请在将任何学生对象插入您的列表之前进行检查,如果它已经存在,则需要这样做。

标签: java arrays object duplicates


【解决方案1】:

现在,由于您不应该使用集合,您可以做的是遍历您的 studentArray 以检查当前 ID 是否已存在于数组中。如果它不存在,则插入,否则跳过它。 以下代码 sn -p 可以提供帮助:

 int size = studentArray.length;
 System.out.print("Insert Student ID: ");
 int ID = sc.nextInt();
 System.out.print("Insert Student Name: ");
 String name = sc.next();
 System.out.print("Insert Student Age: ");
 int age = sc.nextInt();
 int i=0
 for(;i<size;i++){
 if(studentArray[i].ID==ID)
   break;
    }
 if(i==size){
 Student student1 = new Student(name,age,ID);    
 studentArray[size] = student1;
 size++;
 System.out.print("\nStudent Inserted!\n");
  }
 else{
  System.out.print("\nStudent with the given ID is already present in the array!\n");
  }

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2021-05-20
    • 2017-08-03
    相关资源
    最近更新 更多