Why would the following code give me a runtime error? It gives me a thanks Brian AS @MikeProcrup says, when you close the first scanner ( 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 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
stdin ), you are closing
System.in Therefore the second scanner can not read it now and a
public class st {private
No comments:
Post a Comment