猿问

如何修复运行时错误 - 线程“主”java.util.无缓存元素异常中的异常

我在尝试运行程序时收到以下错误。这实际上是对黑客排名的“第6天让我们回顾一下”挑战的提交。


线程“主要”中的异常 java.util.NoSuchElmentexceptexcept.util.scanner.throw(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1371) at Solution.main(Solution.java:10)


这是我的代码:


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("");


    }

}


慕森卡
浏览 80回答 2
2回答

慕田峪4524236

试试这个public static void main(String[] args) {&nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; int T = sc.nextInt();&nbsp; &nbsp; for(int i=0; i<=T; i++){&nbsp; &nbsp; &nbsp; &nbsp; if(!sc.hasNext()) break;&nbsp; &nbsp; &nbsp; &nbsp; String S = sc.next();&nbsp; &nbsp; &nbsp; &nbsp; for(int j=0; j<S.length(); j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(j%2==0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(S.charAt(j));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" ");&nbsp; &nbsp; &nbsp; &nbsp; for(int r=0; r<S.length(); r++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(r%2!=0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(S.charAt(r));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("");&nbsp; &nbsp; }}java.util.NoSuch元素异常在没有下一个元素时被抛出。为了避免这种情况,您应该使用下一页()进行检查。阅读更多详细信息: https://www.tutorialspoint.com/java/util/scanner_hasnext.htm

慕妹3242003

你的代码是完全没问题的。没有必要放置一个hasNext()方法,因为你没有使用集合或数组,我刚刚测试了你的代码,它运行良好。你的错误一定是因为别的东西
随时随地看视频慕课网APP

相关分类

Java
我要回答