[英]How to fix runtime error - Exception in thread “main” java.util.NoSuchElementException
I'm getting the following error while trying to run my program. 我在尝试运行程序时遇到以下错误。 This is actually a submission for Hackerrank's "Day 6 Let's review" challenge. 这实际上是对Hackerrank的“Day 6 Let's review”挑战的提交。
Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1371) at Solution.main(Solution.java:10) java.util.Scanner.throwFor(Scanner.java:862)中的线程“main”java.util.NoSuchElementException中的异常,位于解决方案域的java.util.Scanner.next(Scanner.java:1371)(Solution.java: 10)
Here is my code: 这是我的代码:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int i=0; i<=T; i++){
String S = sc.next();
for(int j=0; j<S.length(); j++){
if(j%2==0){
System.out.print(S.charAt(j));
}
}
System.out.print(" ");
for(int r=0; r<S.length(); r++){
if(r%2!=0){
System.out.print(S.charAt(r));
}
}
System.out.println("");
}
}
Try this 尝试这个
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int i=0; i<=T; i++){
if(!sc.hasNext()) break;
String S = sc.next();
for(int j=0; j<S.length(); j++){
if(j%2==0){
System.out.print(S.charAt(j));
}
}
System.out.print(" ");
for(int r=0; r<S.length(); r++){
if(r%2!=0){
System.out.print(S.charAt(r));
}
}
System.out.println("");
}
}
java.util.NoSuchElementException is thrown when there is no next element. 没有下一个元素时抛出java.util.NoSuchElementException。 To avoid this you should check by using hasNext(). 为避免这种情况,您应该使用hasNext()进行检查。
Read this for more details : https://www.tutorialspoint.com/java/util/scanner_hasnext.htm 阅读本文以获取更多详细信息: https : //www.tutorialspoint.com/java/util/scanner_hasnext.htm
You're code is perfectly fine. 你的代码非常好。 There's no need to put a hasNext() method as you are not working with collections or arrays I just tested your code, and it works well. 没有必要放一个hasNext()方法,因为你没有使用我刚刚测试过代码的集合或数组,而且效果很好。 You error must be for something else 你的错误必须是其他的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.