# How to sum up elements of an arraylist having type String?

Ziya Bakan
Greenhorn
Posts: 13

I have an arraylist consisting of decimal numbers and i m supposed to take the average of last 4 elements of this arraylist.And these rational number are type of String.

private void average(String confidence) {

if(myList.size() >= 4) {

String t = myList.get(myList.size()-1);
String d = myList.get(myList.size()-2);
String f = myList.get(myList.size()-3);
String h = myList.get(myList.size()-4);

String s = (t + d + f+h) ;
long fin = Long.parseLong(s);
long result = fin/4 ;
System.out.println("average is: "+result);
}

but this method does not work.Could you please tell me what kind of changes am i supposed to do or any advices of doing this? Thanks a lot in advance!!!

Aj Prieto
Ranch Hand
Posts: 75
Try printing out the variable "s".

You'll see why it's not working.

Also, why are you taking in values as Strings? Why not just take them in as doubles?

Greg Charles
Sheriff
Posts: 2985
12
• 1
First, please UseCodeTags. Your code has all the right pieces, but not in exactly the right order. Adding strings is not the same as adding numbers. 2 + 2 is 4, but "2" + "2" is "22". What you need to do is convert each string to a number before adding them together.

Also, to get the average of four numbers you'll need to divide by 4, not 3. There's also the issue of integer vs. floating point arithmetic, but it may not be an issue for your assignment. I'd say to get the rest working, and then we'll talk about what's happening to the fractions if necessary.

Ziya Bakan
Greenhorn
Posts: 13
Greg Charles wrote:First, please UseCodeTags. Your code has all the right pieces, but not in exactly the right order. Adding strings is not the same as adding numbers. 2 + 2 is 4, but "2" + "2" is "22". What you need to do is convert each string to a number before adding them together.

Also, to get the average of four numbers you'll need to divide by 4, not 3. There's also the issue of integer vs. floating point arithmetic, but it may not be an issue for your assignment. I'd say to get the rest working, and then we'll talk about what's happening to the fractions if necessary.

if(myList.size() >= 4) {

Long t = Long.parseLong(myList.get(myList.size()-1));
Long d = Long.pareseLong(myList.get(myList.size()-2));
Long f = Long.parseLong(myList.get(myList.size()-3));
Long h = Long.parseLong(myList.get(myList.size()-4));

Long s = (t + d + f+h) ;
Long result = s/4 ;
System.out.println("meanAsrConfidence is: "+result);
}

i changed it like this but still does not work...one additional info os these elements of the arraylist are all rational numbers!!! ???

Jesus Angeles
Ranch Hand
Posts: 2068
Ziya Bakan wrote:still does not work...