1

this the code which i wrote on Jcreator & worked perfectly. But when i tried running on CodeChef's ide [JAVA (javac 8)]. It gave runtime error as follows:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Codechef.main(Main.java:14)

Code is as follows:-

import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef {
    public static void main (String[] args) throws java.lang.Exception {
        Scanner s =new Scanner(System.in);
        int n=s.nextInt(); //error points to this line
        int k=s.nextInt();
        int a[]=new int[n+1];
        int sum=1,x=1,y=n;
        for(int i=1; i<=n; i++) {
            a[i]=s.nextInt();
        }
        while(x!=n) {
            int temp=a[y]-a[x];
            if(temp>=1 && temp<=k) {
                sum=sum+y;
                x=y;
                y=n;
            } else {
                y--;
            }
        }
        System.out.println(sum);
    }
}

What is wrong and how do i rectify it? Please help.

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33
jenit
  • 31
  • 1
  • 1
  • 4

1 Answers1

4

This exception comes when there are no more integers to be inputted. A check if there are any more integers left in input, before inputting the integer can fix this.

For example, you could modify your array input snippet as follows:

for(int i=1;i<=n;i++)
    if(s.hasNextInt())
        a[i]=s.nextInt();
Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33