试图将 String 转换为 Double 但得到 NumberFormatException
Trying to convert String into a Double but getting NumberFormatException
我在这里要做的是,我试图从我的文本中读取数字“1 2 3”,numbers.txt
。从那里,我试图将它设置为一个字符串变量,三。从这里开始,我试图将其转换为双精度数,以便我可以使用这些数字来计算它们的平均值。我不断收到此错误:
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;
你做到了:
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));
举个例子:
1 2 3// 5 12 14 6 4 0 // 1 2 3 4 5 6 7 8 9 10// 17// 2 90 80
如果字符串中只有一个space,那么只拆分求平均值就很容易了。但是您的字符串同时具有 space 和 //.
您可以采用两种方法。
使用 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 已由您定义。 container 是一个 ArrayList 来保存最后的双数。其他变量temp1,s1,temp2,s2是临时数组和字符串,用来操作原始字符串
首先,我在您的字符串中拆分 "//"。然后我使用 space 拆分。现在,由于您的字符串格式不正确,因此在拆分时会有一些随机的空字符串形成临时数组。因此,当我将它们解析为 double 时会出现错误。这就是为什么代码中有一个try-catch。
你得到了 NumberFormatException
因为 1 2 3
不是代表 double
的字符串;相反,它是一个包含数字的字符串。
您可以读取每一行,将值拆分为空格,将值(通过拆分行获得)解析为 double
并求出它们的平均值。
使用流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);
}
}
}
我在这里要做的是,我试图从我的文本中读取数字“1 2 3”,numbers.txt
。从那里,我试图将它设置为一个字符串变量,三。从这里开始,我试图将其转换为双精度数,以便我可以使用这些数字来计算它们的平均值。我不断收到此错误:
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;
你做到了:
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));
举个例子: 1 2 3// 5 12 14 6 4 0 // 1 2 3 4 5 6 7 8 9 10// 17// 2 90 80
如果字符串中只有一个space,那么只拆分求平均值就很容易了。但是您的字符串同时具有 space 和 //.
您可以采用两种方法。
使用 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 已由您定义。 container 是一个 ArrayList 来保存最后的双数。其他变量temp1,s1,temp2,s2是临时数组和字符串,用来操作原始字符串
首先,我在您的字符串中拆分 "//"。然后我使用 space 拆分。现在,由于您的字符串格式不正确,因此在拆分时会有一些随机的空字符串形成临时数组。因此,当我将它们解析为 double 时会出现错误。这就是为什么代码中有一个try-catch。
你得到了 NumberFormatException
因为 1 2 3
不是代表 double
的字符串;相反,它是一个包含数字的字符串。
您可以读取每一行,将值拆分为空格,将值(通过拆分行获得)解析为 double
并求出它们的平均值。
使用流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);
}
}
}