Skip to content

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(
    at java.base/jdk.internal.math.FloatingDecimal.parseDouble(
    at java.base/java.lang.Double.parseDouble(
    at java.base/java.lang.Double.valueOf(
    at Main.main(

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
2 90 80
import java.util.Scanner;

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




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;
double average = sum / count;
User contributions licensed under: CC BY-SA
3 People found this is helpful