尝试将字符串转换为双精度浮点数,但出现了NumberFormatException错误。

huangapple go评论65阅读模式
英文:

Trying to convert String into a Double but getting NumberFormatException

问题

以下是翻译好的内容:

What I'm trying to do here is, I'm trying to read the numbers "1 2 3" from my text, `numbers.txt`. From there, I'm trying to set it into a string variable, three. From here, I'm trying to convert it into a double so that I can use the numbers to find the average of them. I keep getting this error:

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)

I do apologize if this question has been asked in the past. I've looked into this error, as well as looking into anyone else who has asked similar questions on this website and still haven't found an answer.

Edit: I should've also added that, I have to find the average of 5 sets of numbers:

1 2 3 
5 12 14 6 4 0 
1 2 3 4 5 6 7 8 9 10
17
2 90 80

英文:

What I'm trying to do here is, I'm trying to read the numbers "1 2 3" from my text, numbers.txt. From there, I'm trying to set it into a string variable, three. From here, I'm trying to convert it into a double so that I can use the numbers to find the average of them. I keep getting this error:

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)

I do apologize if this question has been asked in the past. I've looked into this error, as well as looking into anyone else who has asked similar questions on this website and still haven't found an answer.

Edit: I should've also added that, I have to find the average of 5 sets of numbers:

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);



		}
	}

答案1

得分: 2

不必读取整行,你可以通过使用nextDouble()Scanner为你处理繁重的工作:

double sum = 0.0;
int count = 0;
while (in.hasNextDouble()) {
    double d = in.nextDouble();
    sum += d;
    count++;
}
double average = sum / count;
英文:

Instead of reading the entire line, you could let the Scanner do the heavy lifting for you by use nextDouble():

double sum = 0.0;
int count = 0;
while (in.hasNextDouble()) {
    double d = in.nextDouble();
    sum += d;
    count++;
}
double average = sum / count;

答案2

得分: 1

看这个例子:

1 2 3// 5 12 14 6 4 0 // 1 2 3 4 5 6 7 8 9 10// 17// 2 90 80

如果字符串中只有一个空格,那么只需简单地进行分割并计算平均值。但是你的字符串中既包含空格又包含*//*。

有两种方法可以处理这个问题。

  1. 使用正则表达式识别字符串中的数字并将它们添加到一个sum变量中,然后计算平均值。如果最终字符串中有双位数,可能需要使用StringBuilder。参考这里的正则表达式:链接

  2. 使用循环和数组两次分割字符串;将结果存储在另一个数组或列表中;从中计算平均值。

我已经采用了第二种方法。虽然有点混乱,但容易理解。

以下是代码:

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());
}

filein 已经由你定义。container 是一个 ArrayList,用于保存最终的双精度数字。其他变量 temp1, s1, temp2, s2 是用来操作原始字符串的临时数组和字符串。

首先,我使用 "//" 对字符串进行了分割。然后,我使用 空格 进行分割。现在,由于你的字符串格式不正确,在分割时会产生一些随机的空字符串,这些空字符串在解析为双精度数时会导致错误。这就是代码中为什么有一个 try-catch 块的原因。

英文:

Take this example:
1 2 3// 5 12 14 6 4 0 // 1 2 3 4 5 6 7 8 9 10// 17// 2 90 80

If there is only a space in the string, it would be easy to just split and find the average. But your string has both space and //.

There are two approaches you could do for this.

  1. Use regex to identify numbers in your string and added them to a sum variable and then find the average. You may need to use StringBuilder if there are any double digits in the final string. Refer regex here: 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.

  2. Use loops and arrays to split your string two times; store the result in another array or a list; find the average from that.

I've done the 2nd way. It's a little messy but simple to understand.

Here is the code:

public static void main(String[] args) throws FileNotFoundException {

        File file = new File(&quot;numbers.txt&quot;);
        Scanner in = new Scanner(file);

        List&lt;Double&gt; container = new ArrayList&lt;&gt;();
        String[] temp1 = in.nextLine().split(&quot;//&quot;);
        for (String s1 : temp1) {
            String[] temp2 = s1.split(&quot; &quot;);
            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(&quot;Average: %.2f\n&quot;, sum/container.size());
    }

file and in are already defined by you. container is an ArrayList to hold the final double numbers. Other variables temp1, s1, temp2, s2 are temporary arrays and string to manipulate the original string.

First I split the "//" in your string. Then I split using space. Now, since your string is not properly formatted, there will be some random empty strings form into the temporary arrays when splitting. Hence there will be error when I parse them as double. That's why there is a try-catch in the code.

答案3

得分: 0

你需要做的是:

Scanner in = new Scanner(System.in);
in.useLocale(Locale.ENGLISH);   // 应明确设置为正确处理小数点
double sum = 0;
int total = 0;

while (in.hasNextDouble()) {
    total++;
    sum += in.nextDouble();
}

System.out.println("avg: " + (sum / total));
英文:

You do:

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)

You should do following:

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(&quot;avg: &quot; + (sum / total));

答案4

得分: 0

你遇到了 `NumberFormatException`,因为 `1 2 3` 不是表示一个 `double` 的字符串;相反,它是一个包含数字的字符串。

你可以读取每一行,按空格分隔值,将通过分隔行获得的值解析为 `double`,然后找出它们的平均值。

**使用 Stream API:**

```java
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);
        }
    }
}

<details>
<summary>英文:</summary>

You got the `NumberFormatException` because `1 2 3` is not a string representing a `double`; rather, it is a string which contains numbers.

You can read each line, split the values on whitespace, parse the values (obtained by splitting the line) into `double` and find their average.

**Using 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(&quot;numbers.txt&quot;);
    		Scanner in = new Scanner(file);
    		while (in.hasNextLine()) {
    			double lineAvg = Arrays.stream(in.nextLine().split(&quot;\\s+&quot;))
    								.mapToDouble(Double::parseDouble)
    								.average()
    								.getAsDouble();
    			System.out.println(lineAvg);
    		}
    	}
    }

**Output:**

    2.0
    6.833333333333333
    5.5
    17.0
    57.333333333333336

**Without using 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(&quot;numbers.txt&quot;);
    		Scanner in = new Scanner(file);
    		while (in.hasNextLine()) {
    			String line = in.nextLine();
    			String[] arr = line.split(&quot;\\s+&quot;);
    			double sum = 0;
    			for (String s : arr) {
    				sum += Double.parseDouble(s);
    			}
    			double lineAvg = sum / arr.length;
    			System.out.println(lineAvg);
    		}
    	}
    }

</details>



huangapple
  • 本文由 发表于 2020年9月13日 04:21:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63864600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定