gpt4 book ai didi

java - 扫描关闭会造成麻烦,所以我应该不关闭它吗?

转载 作者:行者123 更新时间:2023-11-29 05:40:32 25 4
gpt4 key购买 nike

刚从 Python 切换到 Java,在读取用户输入时遇到了一些问题。我在以下代码中有两个问题:(1) 为什么我关闭scanner后不能正常工作(如果是skip close,是不是有问题?)(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;
}
}

这是注释掉扫描关闭的输出:

Enter a numeric value: 1.01
Enter a numeric value: 2.02
The answer is: 3.0300000000000002 (weird output)

如果我取消对 scan.close() 的注释,您将无法键入第二个数字并附上错误消息:

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)

如果你们中的任何人能指出我正确的地方或给我一些关于这两个问题是如何产生的提示,我们将不胜感激!

最佳答案

在第一个输入结束时,您关闭 流。您关闭的流是“标准输入流”。 Scanner 在您调用 close() 时关闭底层流。

在第一次调用您的getInput(String) 方法后,所有从“标准输入流”读取的尝试都将失败。

捕获 Exception 是不好的。当它无法读取流时,您返回 "DEFAULT"Double.parseDouble(..) 提示字符串错误。

关于java - 扫描关闭会造成麻烦,所以我应该不关闭它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17775499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com