0

I have a string like

String str = "102, 308, 409.5";

and I want to add the numbers in the string 102+308+409.5 and keep the result in variable. How can I achieve that?Thanks

Note I was trying to convert the string to string array and then to int array in the below code, but doesn't works.

int sum = 0;

String[] arr = str.split(",");
int[] numArr = new int[arr.length];

for(int i=0; i<arr.length; i++){

numArr[i] = Double.parseDouble(arr[i]);

sum+=numArr[i];

}
2

2 Answers 2

1

I'd give this a go:

double sum = 0;

String[] arr = str.split(",");
double[] numArr = new int[arr.length];

for(int i=0; i<arr.length; i++){

numArr[i] = Double.parseDouble(arr[i]);

sum+=numArr[i];

}

If you are going to parseDouble you need to put that into a double variable, whether that is an array, or just a standard variable.

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

1 Comment

My mistake, was keeping double in int. Thanks for pointing that out.
0

ok, and why is the numArr[] in first place :)

double sum = 0;

String[] arr = str.split(",");
//double[] numArr = new int[arr.length];//delete this

for(int i=0; i<arr.length; i++){

numArr[i] = Double.parseDouble(arr[i]);

// sum+=numArr[i];//delete this

sum+=Double.parseDouble(arr[i]);

}

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.