# Thread: Very basic java problem

1. Newbies
Join Date
May 2011
Posts
2
Rep Power
0

## Very basic java problem

I'm brand new to programming so this may seem stupid. I have a problem where i've made an array of ten double numbers in one class and i have to make a method in another class that adds all of these numbers together using a "for" loop and utilizing the array's length number. I've searched and searched for how to do this and i cannot figure out how it's done. i can get the numbers to print out but i cannot get them to add. Here's what i have:

Java Code:
public void sumDoubles(double[] f) {
double sum = 0;
for(int g = 0;g<f.length;g++){
sum +=f[g];
System.out.println(sum);
}
any help would be great thanks
Last edited by JosAH; 05-26-2011 at 06:13 PM. Reason: added [code] ... [/code] tags around the program code

2. You're adding those numbers correctly but you're not doing anything with the sum, i.e. aren't you supposed to return it from the method?

kind regards,

Jos

3. Newbies
Join Date
May 2011
Posts
2
Rep Power
0
If i'm following correctly, then yes if the numbers are adding correctly i need the method to give the sum when ran. I just don't know how to do this exactly

4. Look at this in the Java Tutorial:

5. try this. you will have to clean up the decimal places though, but you can use a NumberFormat method for that:

{
public static void main(String[] args)
{
double[] tenNumbers = {1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1};
double finalSum;
System.out.println(finalSum);

}

{
}
public static double SumAdd(double[] getArray)
{
double sum = 0;

for (int i = 0; i < getArray.length; i ++)
{
sum += getArray[i];

}

return sum;
}
}

6. Originally Posted by Joel
try this. you will have to clean up the decimal places though, but you can use a NumberFormat method for that:
Please compile and test your code for correctness before you post it.

kind regards,

Jos

7. Jos-
compiles and runs just fine, but I should have cleaned up the open/close brackets to look more conventional. thanks...

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•