Getting array out of bound exception in given problem



  • import java.util.Scanner;
    
    public class MinNumberOfRefuelling  {
    	
    	private static int MinRefuells (int a[],int L,int n)
    	{
    		int numRefills  = 0;
    		int currRefills = 0;
    		while(currRefills < n)
    		{
    			int lastRefill = currRefills;
    			while((currRefills<n) && (a[currRefills+1]-a[lastRefill]<=L))
    			{
    				currRefills+=1;
    			}
    			
    		if(currRefills == lastRefill)
    		{
    			return -1;
    		}
    		if(currRefills<=n)
    		{
    			numRefills+=1;
    		}
    		}
    	return numRefills;
    	}
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		int total_len=sc.nextInt();
    		int maxdistWithoutFuel = sc.nextInt();
    		int n = sc.nextInt();
    		int[] arr = new int[n];
    		for(int i=0;i<arr.length;i++)
    		{
    			arr[i] = sc.nextInt();
    		}
    		System.out.println(MinRefuells(arr,maxdistWithoutFuel,n));
    }
    }
    
    

    when i try to run this program for solving minimum number of refuelling problem i got array out of bound exception for last index values of array. Can anyone explain what can be done.
    In this programming question We are going to travel to another city that is located total_len miles away from your home city. Your car can travel at most maxdistWithoutFuel miles on a full tank and you start with a full tank. Along your way, there are gas stations at distances arr1, arr2, . . . , arr𝑛 from your home city. What is the minimum number of refills needed?



  • Hey @Ayush-gwari

    Because at some point currRefills will equal to 2 and 2 + 1 will be 3 but the size of the the array 'a' is 3 so the highest index is 2 not 3 so it will trigger a out of bounds exception.

    while((currRefills<n) && (a[currRefills+1]-a[lastRefill]<=L))
    			{
    				currRefills+=1;
    			}
    

    So more specifically

    a[currRefills+1]
    

    is causing the out of bounds exception.



  • Hey @Ayush-gwari

    Because at some point currRefills will equal to 2 and 2 + 1 will be 3 but the size of the the array 'a' is 3 so the highest index is 2 not 3 so it will trigger a out of bounds exception.

    while((currRefills<n) && (a[currRefills+1]-a[lastRefill]<=L))
    			{
    				currRefills+=1;
    			}
    

    So more specifically

    a[currRefills+1]
    

    is causing the out of bounds exception.



  • Hey @Ayush-gwari

    Did that work for you? If so, do you mind marking my answer as the correct one. Thank you.


Log in to reply