当前位置: 首页 > 知识库问答 >
问题:

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

淳于坚壁
2023-03-14
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
    }

我在这里遇到错误。而(ve

共有2个答案

楚雪松
2023-03-14

首先:如果数组列表的长度是10,那么有效的索引是从0到9。

所以你应该像这样事先检查你的数组列表的大小:

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

或者像这样使用try-catch:

try {
    vehicleList.get(i);
} catch (Exception e) {
    // you can log exception here
}
窦弘义
2023-03-14

尝试以下代码替换您的代码

int ve= input.nextInt();//用户输入车辆的 S/No 这一行,代码如下

 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
 }
 类似资料: