0
import java.util.Scanner;


public class Taxi {

    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        int groups = input.nextInt();
        int counter=0;

        int[] pass = new int[groups];

        for(int i=0; i<groups; i++){
            pass[i] = input.nextInt();
        }

        for(int i=0; i<groups; i++){
            if(pass[i]==4)
                counter++;

            else if(pass[i]+pass[i+1]<=4){
                counter++;
                i++;
            }
            else 
                counter++;
        }

        System.out.println(counter);
    }

}

keep on receiving error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at Taxi.main(Taxi.java:21)

please help

1
  • This is a perfect time to learn to read error logs and basic debugging, it will save you a lot of time. Commented May 28, 2014 at 18:14

2 Answers 2

3

This line appears to be causing the exception:

else if(pass[i]+pass[i+1]<=4){

You're limiting i to be less than groups, which is the size of the array, but then you deliberately run off the end by using i+1.

Check if i is less than one less than groups first.

else if ( (i < groups - 1) && (pass[i]+pass[i+1]<=4)){
Sign up to request clarification or add additional context in comments.

Comments

0

else if(pass[i]+pass[i+1]<=4) line is your killer definitely.

the reason is you are using for loop with i < groups

 for(int i=0; i<groups; i++)

so i+1 goes to equals to groups for the last iteration.

say for example , it the groups size is 5 then for loop becomes

for(int i=0;i<5;i++)

we can have group[0] ... groups[4] max and groups[5] causes array index out of bound exception.

if we check for loop like above then when i goes to 4 then it satisfies for loop check as 4<5 and enters for loop but there you are doing pass[i] -> ok but pass[i+1] will become like pass[5] which definitely causes array index out of bound exception

so check for loop like below

 for(int i=0; i<groups-1; i++)

it will work now even for the last element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.