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

时间:2015-02-05 12:27:51

标签: java

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
    }

我在这里遇到错误。 while(ve&gt; availableList.size()||(!v.isAvailable())) 我的意思是它可以编译,但是为了验证,它给了我一个错误。 availableList包含10辆车。当我输入0或11辆车时,它给我一个错误:线程“main”中的异常java.lang.IndexOutOfBoundsException:索引:10,大小:10。根据我的while语句,我不认为有什么不对。有谁知道如何解决这个问题?感谢

2 个答案:

答案 0 :(得分:1)

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

所以你应该事先检查你的ArrayList的大小:

if(i >= 0 && i < vehicleList.size()){
   vehicleList.get(i);
   ...
} else {
   ...
}

像这样使用try-catch:

try {
    vehicleList.get(i);
} catch (Exception e) {
    // you can log exception here
}

答案 1 :(得分:1)

尝试以下代码

之后替换你的代码

int ve= input.nextInt();//user input for S/No of vehicle此行包含以下代码

 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
 }