如果我要求用户输入一个 int,并且需要在检查该索引处的数组以查看它是否不为空之前检查它是否在数组的索引范围内,这是否是“短路”的示例?因为如果数组大小只有 5 并且用户输入 15,那么我会得到一个 ArrayIndexOutOfBoundsException。但是如果我先检查输入的数字是否包含0-4,然后再检查数组索引,则可以保证在0-4之间。所以我的问题是:这是“短路”的一个例子吗?我会改写我在代码中所说的话......
import java.util.Scanner;
public Class Reservation{
Customer[] customers = new Customer[5];
Scanner input = new Scanner(System.in);
//some code
private void createReservation(){
System.out.print("Enter Customer ID: ");
int customerIndex;
if(input.hasNextInt()){
customerIndex = input.nextInt();
//is the if-statement below a short-circuit
if(customerIndex < 0 || customerIndex >= 5 || customers[customerIndex] == null){
System.out.print("\nInvalid Customer ID, Aborting Reservation");
return;
}
}
else{
System.out.print("\nInvalid Customer ID, Aborting Reservation");
}
//the rest of the method
}
}