1

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

    }
}
Amin Mozhgani
  • 604
  • 1
  • 7
  • 22

2 Answers2

0

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

Rohit
  • 495
  • 9
  • 16
  • Here is the docs for the exception : https://docs.oracle.com/javase/8/docs/api/java/util/NoSuchElementException.html – Rohit Mar 30 '19 at 06:00
  • Here is an already answered question : https://stackoverflow.com/questions/19106753/java-util-nosuchelementexception-using-iterator-in-java – Rohit Mar 30 '19 at 06:02
  • I think this is repeat but not sure – Rohit Mar 30 '19 at 06:03
0

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