CSV用户登录函数仅首个用户可用的问题排查与修复咨询
问题修复方案
核心问题分析
你的代码存在两个致命逻辑错误:
- 循环每迭代一次,只要当前用户用户名不匹配就立刻抛出异常,直接终止循环,完全没机会校验后续用户,这就是只有第一个用户能登录的原因。
- 即使用户名和密码都验证成功,执行完菜单跳转后,代码依然会执行
throw new IllegalArgumentException("password is incorrect. "),导致异常被抛出。
修改后的代码
private static void signIn(CarDealership carDealership, Scanner scnr, ArrayList<Customer> customerList, Car carInUse) { String userNameAttempt; String passWordAttempt; try { System.out.println("Enter username:"); userNameAttempt = scnr.next(); // 先遍历所有用户,查找匹配的用户名 Customer matchedCustomer = null; for (Customer customerU : carDealership.getCustomerList()) { if (customerU.getUserName().equals(userNameAttempt)) { matchedCustomer = customerU; break; // 找到匹配用户,终止循环 } } // 遍历完所有用户后,判断是否找到匹配用户名 if (matchedCustomer == null) { throw new IllegalArgumentException("username does not exist. "); } // 找到用户后,再要求输入密码 System.out.println("Enter password:"); passWordAttempt = scnr.next(); if (matchedCustomer.getPassWord().equals(passWordAttempt)) { System.out.println("Welcome " + matchedCustomer.getFullName()); if (matchedCustomer instanceof Admin) { adminMainMenu(carDealership, scnr, matchedCustomer, customerList, carInUse); } else { customerMainMenu(carDealership, scnr, matchedCustomer, customerList, carInUse); } // 登录成功,直接返回,避免执行后续异常抛出逻辑 return; } else { throw new IllegalArgumentException("password is incorrect. "); } } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage() + "Would you like to retry?(1) register yourself?(2) or go back?(3) "); int input = scnr.nextInt(); switch (input) { case 1 -> { System.out.println("-----------------------------------"); signIn(carDealership, scnr, customerList, carInUse); } case 2 -> { System.out.println("-----------------------------------"); registerCustomer(carDealership, scnr, customerList, carInUse); } case 3 -> { System.out.println("-----------------------------------"); beginningSite(carDealership, scnr, customerList, carInUse); } default -> {} } } }
关键修改点
- 新增
matchedCustomer变量,先完整遍历所有用户,找到匹配用户名的用户后再进行后续操作,确保所有用户都被校验。 - 将用户名不存在的异常抛出逻辑移到循环结束后,只有遍历完所有用户都没找到匹配项时才抛出。
- 密码输入逻辑移到找到匹配用户之后,避免出现未输入密码就触发错误提示的问题。
- 登录成功后添加
return语句,终止当前方法,避免后续异常抛出代码执行。 - 修复了管理员用户登录后会同时进入管理员菜单和普通用户菜单的问题(原代码没有else分支,管理员登录后执行完
adminMainMenu会继续执行customerMainMenu)。
内容的提问来源于stack exchange,提问作者Kevin Manoj
相关产品推荐
相关产品推荐

