Calling Scanner.close () throws nosuchelement exception

I have a simple method that displays a command on the screen, scans user input and returns it as a string. If the user login is invalid, it notifies the user and requests it again. This method worked fine, but my instructor mentioned that we should always close the resources, so I went back and added a close method, and now I get a NoSuchElementException every time the method is called, regardless of user input. Here is the code ...

private String getUserString(String userCommand) { System.out.println(userCommand); Scanner scan = new Scanner(System.in); String userinput = scan.nextLine().trim(); if (userinput.isEmpty()){ System.out.println("Invalid choice"); return getUserString(userCommand); } else { return userinput; } } 

Exceptions always point to the line where userinput starts as scan.nextLine (). trim () NOTE * I added scan.close () to each line before each return statement, however I did not include it above.

+4
source share
1 answer

When you close scan , you close System.in , and when you try to re-read it, it throws an exception.

Your instructor is right in one aspect, you should clean up resources only when it comes to System.in .


Instead of reopening the stream every time you need input, you can create your Scanner once and just reuse it where you need to enter:

 public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); System.out.println(getUserString("Write something:", scan)); System.out.println(getUserString("Write something else:", scan)); } private static String getUserString(String userCommand, Scanner scan) { System.out.println(userCommand); String userinput = scan.nextLine().trim(); if (userinput.isEmpty()) { System.out.println("Invalid choice"); return getUserString(userCommand, scan); } else { return userinput; } } 
+3
source

Source: https://habr.com/ru/post/1434548/


All Articles