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语句,我认为没有什么问题。有人知道怎么解决这个问题吗?谢谢
发布于 2015-02-05 12:54:11
尝试下面的代码,然后替换您的代码
用下面的代码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
}发布于 2015-02-05 12:33:17
首先:如果有长度为10的ArrayList,那么有效的索引从0到9。
因此,您应该事先检查ArrayList的大小,如下所示:
if(i >= 0 && i < vehicleList.size()){
vehicleList.get(i);
...
} else {
...
}或使用这样的尝试-捕捉:
try {
vehicleList.get(i);
} catch (Exception e) {
// you can log exception here
}https://stackoverflow.com/questions/28343981
复制相似问题