java - Scan close causes trouble so should I leave it unclosed? -
just switching python java , have problems reading in input user. have 2 questions in following code: (1) why not working after close scanner(if after skip close, problem?) (2) why summation of 2 simple numeric numbers lead inaccurate answer 3.0300000000000002?
import java.util.scanner; public class helloworld { public static void main(string[] args) { string s1 = getinput("enter numeric value: "); string s2 = getinput("enter numeric value: "); double d1 = double.parsedouble(s1); double d2 = double.parsedouble(s2); double result = d1 + d2; system.out.println("the answer is: " + result); } private static string getinput(string prompt){ system.out.print(prompt); scanner scan = new scanner(system.in); string input = "default"; try{ input = scan.nextline(); } catch (exception e){ system.out.println(e.getmessage()); } //scan.close(); return input; } }
this output of commenting out scan close:
enter numeric value: 1.01 enter numeric value: 2.02 answer is: 3.0300000000000002 (weird output)
if uncomment scan.close(), cannot type int second number , error message attached:
enter numeric value: 1.01 enter numeric value: no line found exception in thread "main" java.lang.numberformatexception: input string: "default" @ sun.misc.floatingdecimal.readjavaformatstring(floatingdecimal.java:1241) @ java.lang.double.parsedouble(double.java:540) @ helloworld.main(helloworld.java:10)
if of point me right place or give me hints of how 2 problems come from, appreciated!
at end of first input, close the stream. stream closed "standard input stream". scanner
closes underlying stream when call close()
.
all attempts read "standard input stream" fail after first invocation of getinput(string)
method.
catching exception
bad. return "default"
when fails read stream. double.parsedouble(..)
complains bad string.
Comments
Post a Comment