user14079134
user14079134

Reputation:

What is the difference between java.util.NoSuchElementException and ArrayIndexOutOfBoundsException in Java?

I was solving a problem in Hackerrank when the compiler showed this error "java.util.NoSuchElementException" Problem :Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in your array.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {  
   
    

    public static void main(String[] args) throws IOException {
   
 Scanner sc = new Scanner(System.in);
      

        int n =sc.nextInt();

        int m = sc.nextInt();
        int l=n*m;
        int arr[]=new int[l];
        int max=-1;
        int c=0;
        for(int i=0;i<l;i++)
        {
            int qs=sc.nextInt()-1;
            int qe=sc.nextInt()-1;
            int k=sc.nextInt();
            if(i>=qs+c)
            {
              arr[i]=arr[i-c]+k;
              
              if(i==qe+c)
              {
                  c=c+n;
                  continue;
              }
            }
        }


        for(int i=l-n;i<l;i++)
        {
            if(arr[i]>max)
            {
                max=arr[i];
            }
        }
     System.out.println(max);
}
}

My question is how to resolve the error and whats the difference between the above mentioned errors? Sample input:

5 3
1 2 100
2 5 100
3 4 100
Sample ouput:
200
Explanation

After the first update list will be 100 100 0 0 0.
After the second update list will be 100 200 100 100 100.
After the third update list will be 100 200 200 200 100.
The required answer will be 

Upvotes: 0

Views: 332

Answers (1)

J.Backus
J.Backus

Reputation: 1441

The difference is that some code throws one exception and other code throws the other one.

The primary use of ArrayIndexOutOfBoundsException is, as its name suggests, used when using a bad array index.

NoSuchElementException, by contrast, is used for example in Java collections to indicate that a requested element does not exist. In your case, it's likely that your call to nextInt() on the Scanner is responsible. See the documentation page.

Moral: when calling "someone else's" function, read the documentation to find out what it does.

Your actual problem is that you loop expecting l=n*m (=15) rows of 3 integers, whereas there are only 3 such rows. Looks like you should be looping for 3. But I'm not sure what the function of the value 5 is supposed to be.

Upvotes: 1

Related Questions