【发布时间】:2013-12-18 23:13:49
【问题描述】:
如果我要求用户输入一个 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
}
}
【问题讨论】:
-
短路一般特指
&&和||运算符在可以确定不需要计算右侧操作数时的行为。 -
short circuiting 上的维基百科条目
-
“短路”是一个高度依赖上下文的术语。最熟悉
&&和||运算符,也是编译器控制流优化和某些优化计算情况中的术语。一般来说,它是任何有“快速退出”或“绕过”的方案,当可以证明它是不必要的时,它可以避免某些操作。 -
Yes/no questions about an example are not a good fit for this site。除了最初的提问者之外,这些问题的答案对任何人都很少有用。该站点的目的是创建一个有用的高质量问题和答案的存储库。与其问“这是一个 X 的例子吗”,不如问“什么是 X”。是什么让您认为您的代码没有短路?
标签: java arrays indexoutofboundsexception short-circuiting program-flow