查找用户输入的ID,是否存在于数组的对象的两种写法

//创建键盘录入对象
		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("該用戶不存在");
		}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值