Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I access a method containing Scanner class more than once (with Scanner class variable closed every time at the end of the method), i run into an issue. Here is the snippet of the code, I am having problems with: All I am trying to do is return the string and store it in a local variable in Main().

public static String setName() {
   System.out.println("Type in a person's name: ");
   Scanner scanName = new Scanner(System.in);
   String perName = scanName.nextLine();
   scanName.close();
   return perName;
   }

   public static void main(String[] args) {
   String someName;
   someName = setName();
   someName = setName();


On trying to call the
SetName()
function the second time, I get the following error:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)


What I have tried:

I tried to comment the
scanName.close();
in the SetName() method and the issue is resolved. But I have also tried calling the function and assigning it to a different String variable, which did not work either. I would like to know what went wrong.
Posted
Updated 14-May-18 21:58pm

1 solution

Close the Scanner only when your application has finished with it. See, for instance: java - Can use Scanner only once - Stack Overflow[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900