Dinner Coding Time logo, a very stylized D

NoSuchElementException on CodeHS

NoSuchElementException is an error typically caused by the Scanner class. It shows up consistently on some activities, inconsistently on others-- there's really no way to tell until you see it.

public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputLine = scanner.nextLine(); }
On some assignments, this code snippet can cause a NoSuchElementException.

This isn't your fault. As far as I can tell, it happens when the Grader.java doesn't correctly send the test input to your code. However, there are some annoyingly esoteric ways to fix it.

Try/Catch

try & catch tell Java to ignore specific errors. It's not good coding practice to use this too much, but for this problem, there's not much else you can do.

public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputLine = ""; try { inputLine = scanner.nextLine(); } catch(Exception e) { /* if you want to include some intelligent error handling, you can do that here. otherwise, just leave this block empty */ } }
Using try/catch will have the runtime ignore the error.
Note that the inputLine variable is declared outside the try. This makes sure it'll be accessible later in the method.

Scanner Checking Methods

The Scanner class includes some methods for when you can't be sure about the user's input. This is better practice, but doesn't work on CodeHS sometimes.

public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputLine = ""; if(scanner.hasNextLine()) { inputLine = scanner.nextLine(); } }
Using hasNextLine() to avoid the error.
Note that the inputLine variable is declared outside the if. This makes sure it'll be accessible later in the method.

Combining Solutions

If you're still having the error or your code isn't working the way it's supposed to, try combining both solutions. This is a bit overkill, but it shows your teacher that you know both the proper solution and the practical one!

public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputLine = ""; try { if(scanner.hasNextLine()) { inputLine = scanner.nextLine(); } } //this time, i just left the `catch` block empty catch(Exception e) {} }
Combining try/catch with hasNextLine() to avoid the error.