57423

Issue with java Scanner not taking nextLine on new instance

package sandbox2; import java.util.Scanner; public class Sandbox2 { public static void main(String[] args) { for (int i = 0; i < 5; i++) { String s = askForProperty("Enter value for " + i + ": "); System.out.println(i + " is: " + s); } } private static String askForProperty(String message) { Scanner keyboard = new Scanner(System.in); System.out.print(message); String s = keyboard.nextLine(); keyboard.close(); return s; } }

When i run the above code, it returns the first response PERFECTLY. When it tries to ask for the second response, it returns:

java.util.NoSuchElementException: No line found

Why would it return this error? Each time the method askForProperty is called, the Scanner is a completely new instance! Does it have something to do with System.in as an input stream?

Answer1:

Define your scanner as a class variable and then close it only after you are done with all iterations. In your current setup, when you call keyboard.close you are also closing System.in which makes it unusable later on.

package sandbox2; import java.util.Scanner; public class Sandbox2 { static Scanner keyboard = new Scanner(System.in); // One instance, available to all methods public static void main(String[] args) { for (int i = 0; i < 5; i++) { String s = askForProperty("Enter value for " + i + ": "); System.out.println(i + " is: " + s); } keyboard.close(); //Only close after everything is done. } private static String askForProperty(String message) { System.out.print(message); String s = keyboard.nextLine(); return s; } }

Answer2:

Closing a Scanner causes the underlying InputStream to be closed also. As there is only one System.in, any newly created Scanner objects will not be able to read from the same stream:

keyboard.close();

Close the Scanner in the last.

Answer3:

So,

The chief problem in your code is that you create and close Scanner immediately in every single iteration. That simply does not work. Imagine Scanner as a large connection to your IO that requires quite some assemblage. If you open / close it every single time - You might just find a case where the next command is fired before the connection is opened once again. It's very similar to what you might find in a DB connection as well. The way to prevent it is to have Scanner open BEFORE you start iterating, finish the loop and then close it.

Hence, remove the close() statement from the askForProperty() function and move it to your main. Pass the Scanner keyboard object to the function. Once all the iterations are over - Then close it.

import java.util.Scanner; public class Sandbox2 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); // Initialize the Scanner for (int i = 0; i < 5; i++) { String s = askForProperty("Enter value for " + i + ": ", keyboard); // Pass the Scanner System.out.println(i + " is: " + s); } keyboard.close(); // Close the Scanner now that the work is done. } private static String askForProperty(String message, Scanner keyboard) { System.out.println(message); String s = keyboard.nextLine(); return s; } }

Recommend

  • C++11 variable size POD struct
  • How to handle empty space in url when downloading image from web?
  • iOS - Changing frame of a subview of a subclassed UIView (using storyboard with auto layout enabled)
  • Generic/Unknown HTTP Error with response code 0 using UnityWebRequest
  • How to Save JSON data to SQL server database in C#?
  • Python cosine function precision [duplicate]
  • Form tag not showing up in haml file
  • Use tryCatch within R loop
  • jQuery: add elements until a particular height is reached
  • Reading a file into a multidimensional array
  • Query to find the duplicates between the name and number in table
  • Eloquent update method change created_at timestamp
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Reading JSON from a file using C++ REST SDK (Casablanca)
  • FB SDK and cURL: Unknown SSL protocol error in connection to graph.facebook.com:443
  • Using $this when not in object context
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • Optimizing database types to compact database (SQLite)
  • How do I fake an specific browser client when using Java's Net library?
  • How reduce the height of an mschart by breaking up the y-axis
  • How to add date and time under each post in guestbook in google app engine
  • TFS: Get latest causes slow project reloading
  • Running a C# exe file
  • Perl system calls when running as another user using sudo
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • Google cloud sdk not working when python points python3
  • Is there a mandatory requirement to switch app.yaml?
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • AngularJs get employee from factory
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Is there any way to bind data to data.frame by some index?
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Reading document lines to the user (python)
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?