0

I would like to return an array of double values from the strings. How can I do that? I have been unable to do it with the following....

public static double[] fillArray(String numbers)
{
    String[] answers = numbers.split(",");


    double[] boom = new double[answers];

    for (int index = 0; index < answers.length; index++)
    {
        System.out.println(answers[index]);
    }

    return boom;
}
0

4 Answers 4

3

First of all you have to use length to get the length of the array.

double[] boom = new double[answers.length];

Then, inside the loop, convert the String into double.

boom[index] = Double.parseDouble(answers[index]);

Finally, use try-catch or throw exception from method for the parseDouble()

Sign up to request clarification or add additional context in comments.

Comments

2

First of all double[] boom = new double[answers] doesn't make sense, since answers is an array. You want to do:

double[] boom = new double[answers.length];
for (int i = 0; i < answers.length; ++i) {
  boom[i] = Double.valueOf(answers[i]);
}

in which you use Double.valueOf to convert the String to a double. Mind that the method could raise a NumberFormatException in case the string couldn't be parsed to a double.

Comments

2

Note that you will be soon able to do this in one line using :

public static double[] fillArray(String numbers){
     return Arrays.stream(numbers.split(","))
                  .mapToDouble(Double::parseDouble)
                  .toArray();
}

Comments

1

You need to convert each String to a double.

Which you can do with the Double(String s) constructor or parseDouble(String s)

public static double[] fillArray(String numbers)
{
    double[] boom = new double[answer.length];
    String[] answers = numbers.split(",");

    for (int i = 0; i < answers.length; i++) {
       boom[i] = Double.parseDouble(answers[i]);
    }

    for (int index = 0; index < answers.length; index++)
    {
        System.out.println(answers[index]);
    }

    return boom;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.