这会是短路的一个例子吗?

时间:2013-12-03 02:53:00

标签: java arrays indexoutofboundsexception short-circuiting program-flow

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

2 个答案:

答案 0 :(得分:1)

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

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

此代码仅在假设||在获得true后立即停止评估的情况下工作 - 否则,customers[customerIndex]可以通过无效索引到达,从而触发异常。< / p>

答案 1 :(得分:1)

是的,因为如果你从左到右进行的任何比较都是true,那么不需要对剩下的右边比较进行评估。

另一个例子是:

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

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

相关问题