4

ユーザーに int を入力するように依頼し、そのインデックスの配列をチェックして null でないかどうかを確認する前に、配列のインデックスの範囲内にあるかどうかを確認する必要がある場合、それは「短絡」の例でしょうか? 配列サイズが 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短絡が発生すると、 に&&は 2 つの値が必要trueで、最初の値はfalseであるため、2 番目の比較は評価されません。

于 2013-12-03T02:58:03.507 に答える