Reputation: 19648
Just switching from Python to Java and have some problems with reading in the input from user. I have two questions in the following code: (1) Why it is not working properly after I close the scanner(If after skip close, is it a problem?) (2) Why the summation of two simple numeric numbers lead to inaccurate answer 3.0300000000000002?
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
String s1 = getInput("Enter a numeric value: ");
String s2 = getInput("Enter a 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 is the output of commenting out the scan close:
Enter a numeric value: 1.01
Enter a numeric value: 2.02
The answer is: 3.0300000000000002 (weird output)
If I uncomment the scan.close(), you cannot type int the second number and error message is attached:
Enter a numeric value: 1.01
Enter a numeric value: No line found
Exception in thread "main" java.lang.NumberFormatException: For input string: "DEFAULT"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at HelloWorld.main(HelloWorld.java:10)
If any of you could point me to the right place or give me some hints of how those two problems come from, it would be greatly appreciated!
Upvotes: 1
Views: 179
Reputation: 2727
At the end of the first input, you close the stream. The stream you closed was the "standard input stream". Scanner
closes the underlying stream when you call close()
.
All attempts to read from "standard input stream" will fail after the first invocation of your getInput(String)
method.
Catching Exception
is bad. You return "DEFAULT"
when it fails to read the stream. Double.parseDouble(..)
complains about the bad string.
Upvotes: 2
Reputation: 11209
Closing the scanner closes the underlying stream. In your case System.in. On the second call to getInput your code blows up. Consider using the Singleton pattern to store a single instance of your scanner.
Upvotes: 1