简体   繁体   中英

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.

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)

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. To avoid this you should check by using hasNext().

Read this for more details : 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. You error must be for something else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM