smustie1993
smustie1993

Reputation: 7

Throw an exception - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

How can I throw an exception ( Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException) in this algorithm?

public class H7_Oef2 {
    
    public static void main (String[] args)
    {
        int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};
        int totaal =0;
    
        for (int i=0; i<a.length;i++)
        {
            int sum=1;
            while (a[i] < a[i+1])
            {
                sum +=1;
                i+=1;
            }
            
            if (totaal < sum)
                totaal=sum; 
        
        }

        System.out.printf("Het meest aantal opeenvolgende stijgende getallen is %d%n",totaal);
    }
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20
    at H7_Oef2.main(H7_Oef2.java:15)


Upvotes: 0

Views: 54

Answers (2)

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

You need to update the for loop , running the loop till a.length -1 rather than a.length and also update the while loop condition a[i-1] < a[i]

 for (int i=1; i<a.length-1;i++)
    {
        int sum=1;
        while (a[i-1] < a[i])
        {
            sum +=1;
            i+=1;
        }
        
        if (totaal < sum)
            totaal=sum; 
    
    }

Upvotes: 3

TrayzYT
TrayzYT

Reputation: 1

in the line where you have: "" you gave "a [i + 1]". The loop you created () gives the exact number of repetitions how many digits there are in int [] a. Unfortunately, you are trying to make situations where a [i] is less than a [i + 1]. Which is not possible as a [i] will already use the maximum number of available numbers in int [] a. Therefore it crashes that you are trying to get from int [] and a value that does not exist.

Ps. sorry for my english. This is my first post at this website :)

Upvotes: 0

Related Questions