Java开发图书馆管理系统出现ArrayList索引越界异常求助
问题原因
registration方法完成用户信息添加后执行了this.i++操作,调用registrationdetails方法时,变量i的值已经是1,但你仅向ArrayList中添加了1个元素,数组合法索引范围为0~0,使用索引1读取元素自然触发索引越界异常。
解决方法
方案1:调整查询使用的索引值
最新添加的元素索引为i-1,直接修改registrationdetails方法的读取逻辑即可:
public void registrationdetails(){ System.out.printf("Your name: %s\nYour phone no.: %ld",this.name.get(this.i-1),this.phone_no.get(this.i-1)); }
方案2:调整i自增的时机
将i++移动到registration方法最开头,保证添加元素时用的索引和查询时的索引一致:
public void registration(){ this.i++; System.out.print("Enter your name: "); this.name.add(this.i-1,sc.next()); System.out.print("Enter your phone no.: "); this.phone_no.add(this.i-1,sc.nextLong()); }
方案3(推荐):无需手动维护索引变量
ArrayList本身提供size()方法可以获取当前元素总数,添加元素时直接用无参add()方法自动追加到末尾,不需要手动指定索引:
class library{ Scanner sc = new Scanner(System.in); ArrayList<String> name = new ArrayList<>(); ArrayList<Long> phone_no = new ArrayList<>(); public void registration(){ System.out.print("Enter your name: "); this.name.add(sc.next()); System.out.print("Enter your phone no.: "); this.phone_no.add(sc.nextLong()); } public void registrationdetails(){ int lastIndex = name.size()-1; System.out.printf("Your name: %s\nYour phone no.: %ld",this.name.get(lastIndex),this.phone_no.get(lastIndex)); } }
额外优化建议
建议封装User实体类存储用户的姓名和手机号,仅维护一个ArrayList<User>即可,避免两个独立列表出现索引不匹配的问题。
class User { private String name; private Long phoneNo; // 构造方法、get/set方法自行补充 }
内容的提问来源于stack exchange,提问作者CODER rookie
相关产品推荐
相关产品推荐

