//创建键盘录入对象
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要修改的学生的学号:");
String id = sc.nextLine();
//定义一个索引
int index = -1;
//遍历集合
for(int x=0; x<list.size(); x++) {
//获取每一个学生对象
Student s = list.get(x);
//拿学生对象的学号和键盘录入的学号进行比较
if(s.getId().equals(id)) {
index = x;
break;
}
}
if(index == -1) {
System.out.println("不好意思,你要修改的学号对应的学生信息不存在,请回去重新你的选择");
}else {
System.out.println("请输入学生新姓名:");
String name = sc.nextLine();
System.out.println("请输入学生新年龄:");
String age = sc.nextLine();
System.out.println("请输入学生新居住地:");
String address = sc.nextLine();
以上代码段是较为高大上的写法 (用-1不存在的索引)
以下是自己的思路写出的方法,同样可以实现 (直接搜索数组中的所有对象,搜素完毕没有就修改 是否存在的标志)
Scanner sc =new Scanner(System.in);
System.out.println("請輸入需要修改信息的學生ID");
String input = sc.nextLine();
boolean isExist=true; //判斷是否存在需要修改的用戶
for(int i=0;i<arr.size();i++){
if(input!=null&&input.equals(arr.get(i).getSid())){
isExist=false;
System.out.println("請輸入學生的姓名");
String name = sc.nextLine();
System.out.println("請輸入學生的年齡");
String age = sc.nextLine();
System.out.println("請輸入學生的性別");
String sex = sc.nextLine();
Student s = new Student(input, name, age, sex);
arr.set(i, s);
}
}
if(isExist==true){
System.out.println("該用戶不存在");
}