java - 这是短路的例子吗?

标签 java arrays indexoutofboundsexception short-circuiting program-flow

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

相关文章:

java - 使用 AspectJ 递归

java - 原子整数不当行为

java - jni native 函数重载签名

arrays - 按某些属性对数组的元素进行分组

java - IndexOutOfBoundException 使用 java.util.Vector

java - MySQL 表中的 ArrayIndexOutOfBoundsException

Java-获取 IndexOutOfBoundsException

java - 通过多个字段比较对象,如何在一个方法中添加?

java - 连接 4 检查获胜算法

java - 在数组中查找最小值和最大值时出现 Stackoverflow 错误?