Facing No Such Element Exception in JAVA

why my code https://www.codechef.com/viewsolution/14259829 is gives ERROR on “RUN” and WRONG ANSWER on “SUBMIT” for SNAKPROC…
The error is 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)

One thing i will point out, even if we fix the issue, you will get WA due to printing wrong Output.

The problem statement asked you to print “Valid” “Invalid” while you are printing “invalid” and “valid”. This will surely give WA.

Meanwhile, I am looking at the cause of exception

EDIT: Codechef IDE did not give this exception on sample I/O , so i want to ask where did you get that exception? Can you for possible error in input? (Extra space or extra new line causes this error)

Edit: Moreoever, your logic is wrong. Your code fails for this test case-

Expected Output 

I know, you must be thinking “But i have written proper conditions for it!”

True, but those are undedr “else if” part, and they will never get executed since the condition before them , i.e. "s[i[==‘H’) will return true and will set trig=true. Change that condition (problem is, it is always getting executed so the condition you laid out later to deal with this test case isnt getting executed).

1 Like

In my case, when I saw this error… I was not selecting custom input and passing sample input. What I learned after 10 minutes is that when you click on Run, it does not automatically pick sample input for you. However when you click on submit, it does. So steps are

  1. Write your code
  2. Always do your first run with custom input.
  3. When you find output matching sample output, then do submit.

I hope this helps to new guys who are not used to codechef.


This is the correct reason! Thanks a lot! Anyone facing similar issue, please refer to this solution.

Thank you so much…It really worked for me

Thank you so much. I spent half an hour to solve this… and finally landed on your answer. Thank you !!

Phew!!! I absolutely smacked my head as to why I couldn’t get past this error. Thank you!!
There should have been some hint that showed this near the input box.

This is the correct answer.
After spending hours i found this.
Thanks Buddy.

when I gave custom inputs, its getting successfully executed but when I submitted it, it gave runtime error, any suggestions?

@spit2021600067 - you can check out the faqs here - Why do I get a Runtime exception? - #2 by admin

Typically custom inputs are small - the hidden test cases will be much larger. There could be many thing wrong - you need to check out the thread.