I am practicing some algorithm problems. While I use Scanner to get some input, my program throws a java.util.NoSuchElementException in thread "main", and I really don't know why. It can compile on my IDE (IntelliJ IDEA) and the outcome is right, but when I submit code on OJ web, it throws the aforementioned exception.
The stack trace with the error message of the exception:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.ScannerthrowFor(Scannerjava:937)
at java.base/java.util.Scannernext(Scannerjava:1594)
at java.base/java.util.Scannernextlnt(Scannerjava:2258)
at java.base/java.util.ScannernextInt(Scannerjava:2212)
at Main.main(Main.java:11)
non-zero return = 1
screenshot of my class in the IDE
screenshot of the stack trace in the IDE
My Main class:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int[] nums;
static int[] b;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
nums = new int[n];
b = new int[n];
for(int i = 0; i < n; ++i)
nums[i] = sc.nextInt();
sc.close();
Arrays.sort(nums);
for(int i = 0; i < n - 1; ++i)
b[i] = nums[i + 1] - nums[i];
Arrays.sort(b,0,n - 1);
int d = 0;
for(int j = 0; j < n - 2; ++j){
d = gcd(b[j],b[j + 1]);
b[j + 1] = d;
}
int ans = (nums[n - 1] - nums[0]) / d + 1;
System.out.println(ans);
}
static int gcd(int a,int b){
return b == 0? a: gcd(b,a % b);
}
}
I try to read the source code, but I cannot understand fully the source code. I tried to search for a solution on the web, but I did not find anything about my problem. I would like to know why it throws this exception, and how to fix it to avoid such anomalies.