有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何错误处理数组中的重复学生ID

请帮助我理解,如果存在重复ID,我如何防止插入学生。我正在尝试理解如何避免导入任何内容,尽管我不介意您共享您获得的任何内容,以便我可以学习。谢谢

I tried looping over every object and checking studentArray.getID() if it matches, but I can't seem to get the output right. I also tried storing every ID into another array and comparing both arrays though I think I have to use nested for loop and it broke all my code. I also couldn't get to figure out how I can just set ID to 1, then add 1 to a max of 10 since studentArray[10] is 10. So this code is the cleanest I could provide.

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");

共 (1) 个答案

  1. # 1 楼答案

    既然你不应该使用集合,你可以做的就是迭代你的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");
      }