This question already has an answer here:
这个问题在这里已有答案:
- Scanner error with nextInt() [duplicate] 1 answer
nextInt()[复制] 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:
这是我在Jcreator上写的代码并且工作得很好。但是当我尝试运行CodeChef的ide [JAVA(javac 8)]时。它给出了运行时错误如下:
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.
有什么问题,我该如何纠正呢?请帮忙。
1 个解决方案
#1
2
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();
#1
2
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();