Python から Java に切り替えるだけで、ユーザーからの入力を読み取る際に問題が発生します。次のコードで 2 つの質問があります: (1) スキャナーを閉じた後に正しく動作しないのはなぜですか (スキップ クローズした後、問題はありますか?) (2) 2 つの単純な数値の合計が不正確な答えにつながるのはなぜですか? 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;
}
}
これは、scan close をコメントアウトした出力です。
Enter a numeric value: 1.01
Enter a numeric value: 2.02
The answer is: 3.0300000000000002 (weird output)
scan.close() のコメントを外すと、2 番目の数字に int を入力できなくなり、エラー メッセージが添付されます。
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)
誰かが私に適切な場所を教えてくれたり、これら 2 つの問題がどのように発生したかについてのヒントを教えてくれたりしたら、大歓迎です!