4

如果我要求用户输入一个 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
    }
}
4

2 回答 2

1

是的,这是正确使用短路的有效示例:

if(customerIndex < 0 || customerIndex >= 5 || customers[customerIndex] == null)

此代码仅在以下假设下有效,即||一旦获得true- 就停止评估,否则customers[customerIndex]可能会使用无效索引到达,从而触发异常。

于 2013-12-03T02:57:56.150 回答
1

是的,因为如果从左到右进行的任何比较是true,则不需要评估其余的右侧比较。

另一个例子是:

if(node != null && node.value.equals("something"))

在这种情况下,如果node == null发生短路,因为&&需要两个true值并且第一个是false,所以它不会评估第二个比较。

于 2013-12-03T02:58:03.507 回答