-1

I need to convert a string array to double array in android. But my app is not getting executed on my device. It shows unfortunately stopped.Following is my code:

String dataa="0.121 0.547 0.875 0.245";                                    
String delimiter = " ";

String spectrainstring[] = dataa.split(delimiter);

int size = spectrainstring.length;

double[] spectraldata={0.0};

for(int i=0;i<size;i++)    
{   
    spectraldata[i]=Double.parseDouble(spectrainstring[i].toString());     
}
3
  • Please review the code you posted and make sure it is exactly what you are executing on your local machine. It would also be very nice if you showed us the logcat output as that will tell us what the problem is and what line of code it starts from. Commented Sep 27, 2017 at 18:44
  • 3
    At first glance my guess is that it's an IndexOutOfBounds issue because the double array you are trying to populate has only a length of 1 but you loop until size which in this case is 4. Commented Sep 27, 2017 at 18:45
  • Also any reason not to use a Scanner class? Commented Sep 27, 2017 at 19:17

1 Answer 1

1
String dataa = "0.121 0.547 0.875 0.245";
String delimiter = " ";

String spectrainstring[] = dataa.split(delimiter);

int size = spectrainstring.length;

double[] spectraldata = new double[size];

for (int i = 0; i < size; i++) {
    spectraldata[i] = Double.parseDouble(spectrainstring[i].toString());
    System.out.println(spectraldata[i]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Important line change is double[] spectraldata = new double[size];
Actually sir, I am getting error in parsing the string variable to double. When I comment this line, the other code gets executed.
This line double[] spectraldata = {0.0}; gives you java.lang.ArrayIndexOutOfBoundsException. How it's working for you as there are 4 double values?
I have made a change there as: double[] spectraldata = new double[size];

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.