Click here to Skip to main content
13,895,744 members
Rate this:
Please Sign up or sign in to vote.
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(;
   String perName = scanName.nextLine();
   return perName;

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

On trying to call the
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
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.
Updated 14-May-18 21:58pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web05 | 2.8.190306.1 | Last Updated 15 May 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100