如何解决尝试将String转换为Double但得到NumberFormatException
我在这里想要做的是,我正在尝试从文本numbers.txt
中读取数字“ 1 2 3”。从那里,我试图将其设置为一个字符串变量,三个。从这里开始,我试图将其转换为双精度数,以便可以使用数字来找到它们的平均值。我不断收到此错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1 2 3"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:549)
at java.base/java.lang.Double.valueOf(Double.java:512)
at Main.main(Main.java:13)
对于过去曾问过这个问题,我深表歉意。我调查了此错误,并调查了在此网站上提出类似问题但仍未找到答案的其他任何人。
编辑:我还应该补充一点,我必须找到5组数字的平均值:
1 2 3
5 12 14 6 4 0
1 2 3 4 5 6 7 8 9 10
17
2 90 80
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) throws FileNotFoundException,NumberFormatException {
String three;
File file = new File("numbers.txt");
Scanner in = new Scanner(file);
three = in.nextLine();
double threeconversion = Double.parseDouble(three);
System.out.println(three);
}
}
解决方法
您可以让Scanner
使用nextDouble()
来代替繁重的工作:
double sum = 0.0;
int count = 0;
while (in.hasNextDouble()) {
double d = in.nextDouble();
sum += d;
count++;
}
double average = sum / count;
,
以以下示例为例: 1 2 3 // 5 12 14 6 4 0 // 1 2 3 4 5 6 7 8 9 10 // 17 // 2 90 80
如果字符串中只有一个空格,则很容易拆分并找到平均值。但是您的字符串同时具有空格和 // 。
您可以采用两种方法进行操作。
-
使用 regex 识别字符串中的数字,并将其添加到 sum 变量中,然后找到平均值。如果最终字符串中有任何两位数字,则可能需要使用 StringBuilder 。在此处引用正则表达式:https://javarevisited.blogspot.com/2012/10/regular-expression-example-in-java-to-check-String-number.html#:~:text=In%20order%20to%20check%20for,Pattern%20digitPattern%20%3D%20Pattern。
-
使用循环和数组将字符串拆分两次;将结果存储在另一个数组或列表中;从中找到平均值。
我已经做了第二种方法。有点混乱,但简单易懂。
代码如下:
public static void main(String[] args) throws FileNotFoundException {
File file = new File("numbers.txt");
Scanner in = new Scanner(file);
List<Double> container = new ArrayList<>();
String[] temp1 = in.nextLine().split("//");
for (String s1 : temp1) {
String[] temp2 = s1.split(" ");
for (String s2 : temp2) {
try {
container.add(Double.parseDouble(s2));
} catch (NumberFormatException ignored) {}
}
}
double sum = 0.0;
for (double i : container) sum += i;
System.out.printf("Average: %.2f\n",sum/container.size());
}
您已经定义了file 和 in 。 容器是一个ArrayList,用于保存最终的双精度数字。其他变量 temp1,s1,temp2,s2 是临时数组和用于操作原始字符串的字符串。
首先,我将“ //” 拆分为字符串。然后我使用 space 进行拆分。现在,由于您的字符串格式不正确,因此分割时临时数组中会出现一些随机的空字符串形式。因此,当我将它们解析为double时将出现错误。这就是为什么代码中有 try-catch 的原因。
,您这样做:
three = in.nextLine(); // read the whole line from Scanner
double threeconversion = Double.parseDouble(three); // parse this line to double (and have NFE when line contains more than one number)
您应该执行以下操作:
Scanner in = new Scanner(System.in);
in.useLocale(Locale.ENGLISH); // should be explicitly set to correctly work with decimal point
double sum = 0;
int total = 0;
while (in.hasNextDouble()) {
total++;
sum += in.nextDouble();
}
System.out.println("avg: " + (sum / total));
,
您得到了NumberFormatException
,因为1 2 3
不是代表double
的字符串;而是一个包含数字的字符串。
您可以阅读每一行,将空格中的值分割,将值(通过分割线获得)解析为double
并找到其平均值。
使用Stream API:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String three;
File file = new File("numbers.txt");
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
double lineAvg = Arrays.stream(in.nextLine().split("\\s+"))
.mapToDouble(Double::parseDouble)
.average()
.getAsDouble();
System.out.println(lineAvg);
}
}
}
输出:
2.0
6.833333333333333
5.5
17.0
57.333333333333336
不使用Stream API:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String three;
File file = new File("numbers.txt");
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String line = in.nextLine();
String[] arr = line.split("\\s+");
double sum = 0;
for (String s : arr) {
sum += Double.parseDouble(s);
}
double lineAvg = sum / arr.length;
System.out.println(lineAvg);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。