gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:33:08 25 4
gpt4 key购买 nike

请帮助我了解如何防止在 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");

最佳答案

现在,由于您不应该使用集合,您可以做的是迭代您的 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");
}

关于java - 如何错误处理数组中重复的学生 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60124732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com