Friday 15 February 2013

Using a java.util.Scanner from within a method causes a runtime error -


Why would the following code give me a runtime error? It gives me a NoSuchElementException when the method is called the second time, it works fine if I delete the call at stdin.close () , but then the eclipse One warns that the resource is not closed.

Code:
  Import java.util.Scanner; Public class st {public static zero chief (string [] args) {System.out.println ("first call"); GetInt ("Enter the First Ent (1-10):"); System.out.println ("second call"); GetInt ("Enter second int (1-10):"); } / ** * reads an integer number from the keyboard * * @ indicates the string to display as the ultimate sign * Return the integer number entered on the @ keyboard. * / Public fixed int getInt (string prompt) {scanner stdin = new scanner (System.in); System.out.print (expedited); Int val = stdin.nextInt (); Stdin.close (); Return (val); }} // END   

Output:
  & gt; Enter java st first call first (1-10): 5 second call enter second int (1-10): java.util.Scanner.next at java.util.Scanner.nextInt (unknown source). Source: st.main (st.java:9) & gt;   

on java.util.Scanner.nextInt (unknown source) st.getInt (st.java.24) Java Java code = "Java" version 1.7.0_21 "Java (TM) SE runtime environment (build 1.7.0_21-B11) Java Hotspot (TM) 64-bit server VM (Build 23.21-B01, mixed mode)>

thanks

Brian

AS @MikeProcrup says, when you close the first scanner ( stdin ), you are closing System.in Therefore the second scanner can not read it now and a

  public class st {private   

Scanner stdin = new scanner (System.in); public static zero main (string [] args) {System.out.println ("first call"); GetInt ("Enter the first int (1-10):"); System.out.println ("second call"); GetInt ("Enter second int (1-10):"); } / ** * reads an integer number from the keyboard * * @ indicates the string to display as the ultimate sign * Return the integer number entered on the @ keyboard. * / Public fixed int getInt (string prompt) {System.out.print (expedited); Int val = stdin.nextInt (); Stdin.close (); Return (val); }} / END

No comments:

Post a Comment