java 扫描仪 - codeChef 中的 nextInt 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32357134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scanner - nextInt issue in codeChef
提问by jenit
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.
出了什么问题,我该如何纠正?请帮忙。
回答by Anindya Dutta
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();