Skip to content
Advertisement

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



        }
    }

Advertisement

Answer

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;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement