Java 如何错误处理数组中的重复学生ID
请帮助我理解,如果存在重复ID,我如何防止插入学生。我正在尝试理解如何避免导入任何内容,尽管我不介意您共享您获得的任何内容,以便我可以学习。谢谢 我尝试在每个对象上循环并检查studentArray.getID()是否匹配,但似乎无法获得正确的输出。我还尝试将每个ID存储到另一个数组中,并比较两个数组,尽管我认为我必须使用嵌套for循环,它破坏了我所有的代码。我也无法理解如何将ID设置为1,然后将1添加到最大值10,因为studentArray[10]是10。因此,这段代码是我能提供的最干净的代码Java 如何错误处理数组中的重复学生ID,java,arrays,object,duplicates,Java,Arrays,Object,Duplicates,请帮助我理解,如果存在重复ID,我如何防止插入学生。我正在尝试理解如何避免导入任何内容,尽管我不介意您共享您获得的任何内容,以便我可以学习。谢谢 我尝试在每个对象上循环并检查studentArray.getID()是否匹配,但似乎无法获得正确的输出。我还尝试将每个ID存储到另一个数组中,并比较两个数组,尽管我认为我必须使用嵌套for循环,它破坏了我所有的代码。我也无法理解如何将ID设置为1,然后将1添加到最大值10,因为studentArray[10]是10。因此,这段代码是我能提供的最干净的代
既然你不应该使用集合,你可以做的就是迭代你的studentArray来检查当前ID是否已经存在于数组中。如果不存在,则插入,否则跳过它。 以下代码段可以提供帮助:
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");
}
int size=studentArray.length;
系统输出打印(“插入学生ID:”);
int ID=sc.nextInt();
系统输出打印(“插入学生姓名:”);
字符串名称=sc.next();
系统输出打印(“插入学生年龄:”;
int age=sc.nextInt();
int i=0
对于(;I为什么不使用Set
来避免重复元素?我不确定是否理解,请参考javadoc了解接口。“Student类型不是泛型的。它不能用参数参数化”我不应该使用任何集合如果你不想使用任何集合,请在将任何学生对象插入列表之前检查,如果已经存在,请执行必要的操作。
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");
}