如果我要求用户输入一个 int,并且在检查该索引处的数组以查看它是否不为空之前需要检查它是否在数组的索引范围内,这是否是“short”的示例循环”?因为如果数组大小仅为 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
}
}
最佳答案
是的,这是正确使用短路的有效示例:
if(customerIndex < 0 || customerIndex >= 5 || customers[customerIndex] == null)
此代码仅在 ||
一获得 true
就停止评估的假设下工作 - 否则,customers[customerIndex]
可以使用无效索引访问,从而触发异常。
关于java - 这是短路的例子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20341965/