0

So I can't get this little snipit of code to work and I'm not sure why it wont...

String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");

double[] hold = double.parseDouble(rawInput.split(" "));

I have an idea to use another string array to put the values in initially then put them into the double array using a for loop and the double.parseDouble() but that seems overly complicated for what I want to do.

4 Answers 4

2

Your code fails to compile because rawInput.split(" ") returns an array of String objects. You need just one String object to pass to Double.parseDouble(). It looks like you'll need a loop, to iterate through the array that you get.

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

Comments

0

If only it was that simple. You will have to create a loop.

Comments

0

What I ended up doing was this:

    String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");

    double[] doubleHold = new double[3];
    String[] stringHold = rawInput.split(" ");

    for(int i = 0; i < 3; i++)
    {
        doubleHold[i] = Double.parseDouble(stringHold[i]);
    }

I don't like how it works and think there must be a better way, anyone have that better way?

7 Comments

rawInput.length() is not equal to the number of doubles user enter. It won't work. You will probably get an ArrayIndexOutOfBoundsException.
I just fixed that, my bad
Slightly cleaner to use a for-each loop, but this is more-or-less the correct way to do it.
@DavidWallace What is a for-each loop?
My mistake, sorry. It's not actually an improvement to use a for-each loop.
|
0
String rawInput = JOptionPane.showInputDialog("Please enter the three side lengths seperated by spaces.");
String[] inputs = rawInput.split(" ");
double[] values = new double[inputs.length];
for (int i = 0; i < inputs.length; i++) {
    values[i] = Double.parseDouble(inputs[i]);
}

Try this!

2 Comments

Thats almost exactly what I posted three minutes previous to you.
Yes, lukeb28, (for some small value of "three") but your solution didn't actually work until after Drogba posted this.

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.