Java ArrayList搜索元素触发IndexOutOfBoundsException异常求助
问题根因
- 错误1:搜索起始下标错误。输入结束后
index的值是列表最后一个元素的下标,你没有在每次搜索前重置下标,搜索非末尾元素时直接从最后一个下标开始往后累加,直接超出列表的有效下标范围(列表有效下标范围是0到list.size()-1) - 错误2:没有越界判断逻辑。搜索时如果没找到匹配元素,会一直执行
index++,只要下标超过list.size()-1再调用list.get(index)就会抛出IndexOutOfBoundsException - 错误3:遍历逻辑错误。当前逻辑只会从末尾下标往后查询,永远遍历不到列表前面的元素,非末尾元素永远无法被匹配到。
末尾元素可正常搜索的原因
输入结束后index刚好等于最后一个元素的下标,首次搜索末尾元素时,第一次比对就匹配成功,不会执行index++的逻辑,因此不会触发越界,也能正常输出结果。
修复后的代码
import java.util.ArrayList; import java.util.Scanner; public class IndexOf { public static void main(String[] args) { //Scanner对象 Scanner scanner = new Scanner(System.in); //创建ArrayList ArrayList<Integer> list = new ArrayList<>(); //循环接收用户输入添加到列表 while(true) { //获取用户输入 int user_input = Integer.valueOf(scanner.nextLine()); if(user_input == -1) { break; } else { list.add(user_input); } } // 支持多次搜索 while(true) { //提示用户输入要搜索的数字,搜索后输出对应索引 System.out.print("Search for "); int ask_user = Integer.valueOf(scanner.nextLine()); boolean isFound = false; // 每次搜索重置下标,从0开始遍历 for(int i = 0; i < list.size(); i++) { if(list.get(i) == ask_user) { System.out.println(ask_user + " is at index " + i); isFound = true; break; } } if(!isFound) { System.out.println(ask_user + " is not in the list"); } } } }
内容的提问来源于stack exchange,提问作者Krattza
相关产品推荐
相关产品推荐

