首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >线程“主”java.lang.IndexOutOfBoundsException中的异常:索引: 10,大小: 10

线程“主”java.lang.IndexOutOfBoundsException中的异常:索引: 10,大小: 10
EN

Stack Overflow用户
提问于 2015-02-05 12:27:51
回答 2查看 1.6K关注 0票数 1
代码语言:javascript
复制
Scanner input = new Scanner(System.in);

    ArrayList availableList = new ArrayList();

    for(int i=0;i<vehicleList.size();i++)
    {
      Vehicle v = (Vehicle) vehicleList.get(i);
      if(v.isAvailable())
         availableList.add(v);
    }

    System.out.println("Option 5.Rent A Vehicle");
    listCustomers(customerList);//displays Customers

    System.out.print("Enter S/No of customer:");
    int c1 = input.nextInt();//user input for S/No of customer

    while(c1 > customerList.size() || c1 < 1)//checks if S/No is valid
    {
    System.out.println("Invalid option! please re-enter S/No of customer");
    c1 = input.nextInt();//prompt user to re-enter S/No of customer
    }

    Customer c = (Customer) customerList.get(c1-1); //creates customer object
    listavailableVehicles(availableList);//displays vehicles

    System.out.print("Enter S/No of Vehicle        :");
    int ve= input.nextInt();//user input for S/No of vehicle
    Vehicle v = (Vehicle) availableList.get(ve-1);//creates vehicle object

    while(ve > availableList.size() || (!v.isAvailable()))//check if S/No is valid
    {
    System.out.println("Invalid option! please re-enter S/No of of vehicle");
    ve = input.nextInt();//prompt user to re-enter S/No of vehicle
    v = (Vehicle) vehicleList.get(ve-1);//creates vehicle object
    }

我这里出了点差错。我的意思是它可以编译,但是对于验证,它给了我一个错误。availableList有10辆车。当我输入0或11台车辆时,它会给出一个错误:在线程“java.lang.IndexOutOfBoundsException: 10”中出现异常:索引: 10,大小:10。根据我的When语句,我认为没有什么问题。有人知道怎么解决这个问题吗?谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-05 12:54:11

尝试下面的代码,然后替换您的代码

用下面的代码int ve= input.nextInt();//user input for S/No of vehicle这一行

代码语言:javascript
复制
 Vehicle v=null;
 if(ve > availableList.size() || ve <= 0){
     while(ve > availableList.size() || (!v.isAvailable()))//check if S/No is valid
     {
        System.out.println("Invalid option! please re-enter S/No of of vehicle");
        ve = input.nextInt();//prompt user to re-enter S/No of vehicle

        if(ve <= availableList.size() && ve > 0) {
          v = (Vehicle) vehicleList.get(ve-1);//creates vehicle object
          break;
         }

     }
 }
 else
 {
       v = (Vehicle) availableList.get(ve-1);//creates vehicle object
 }
票数 1
EN

Stack Overflow用户

发布于 2015-02-05 12:33:17

首先:如果有长度为10的ArrayList,那么有效的索引从0到9。

因此,您应该事先检查ArrayList的大小,如下所示:

代码语言:javascript
复制
if(i >= 0 && i < vehicleList.size()){
   vehicleList.get(i);
   ...
} else {
   ...
}

使用这样的尝试-捕捉:

代码语言:javascript
复制
try {
    vehicleList.get(i);
} catch (Exception e) {
    // you can log exception here
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28343981

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档