1. ホーム
  2. Arrays

ArrayIndexOutOfBoundsExceptionが発生しました。7Exception: at Test.m)

2022-02-14 09:43:10
<パス
//Loop through the array values
        int[] sl={
8,4,2,1,23,344,12};
        for(int i=0;i<sl.length;i++){
            System.out.print(sl[i]+"\t");

// Output the sum of the values in the array
int[] sl={
8,4,2,1,23,344,12};
        int sum=0;
        for(int i=0;i<sl.length;i++){
            sum=sum+sl[i];

        }
        System.out.print(sum);  
    }

//Verify that the number exists in the array
        int[] sl={
8,4,2,1,23,344,12};
        Scanner input=new Scanner(System.in);
        System.out.println("Please enter your guess number: ");
        int a=input.nextInt();
        boolean cx=false;//mark guess right for true wrong for false
        for(int i=0;i<sl.length;i++){ // i<=sl.length then there will be an array out of bounds problem, prompting an error
            if(a==sl[i]){
                cx=true;
                break;
            }
        }
        if(cx){
            System.out.println("Guessed right, the number exists");
        }else{
            System.out.println("Guessed wrong, number does not exist");
        }
    }
}

The error hint means that the array is out of bounds, as in the above example, the length of the array you built is 7, respectively sl[0] to sl[6], and sl.length=7, so when you i<=sl.length will take the value 7, and sl[7] is obviously not in the range of the array you built, so the hint is that the array is out of bounds.