Write a Java Method?

2008-05-05 2:29 am
Write a Java method call SumArray which take in an integer array arr and sum up all the values in the array by either a for loop or a while loop and return the sum.

回答 (3)

2008-05-05 2:36 am
✔ 最佳答案
private int SumArray(int[] arr)
{
int total = 0;
for(int i = 0; i < arr.lenght; i++)
{
total += arr[i];
}
return total;
}
this is C# code.... but you should be able to figure it out...
2016-04-03 5:43 pm
public boolean verifySolution( int x, int y ) { ..... // these can be any values you need ..... int a = 5; ..... int b = 10; ..... int c = 100; ..... return ( a * x + b * y == c ); }
2008-05-05 2:36 am
the parameter for the method should be of type int [], and the return value should be an int.

Declare an int variable that will take on the sum.

The for loop will loop according to the condition i < arr.length, in which i is a variable you declare(to be 0) in the for declaration. You then will increase i by one at the end of each iteration of the loop.

In the loop, you will add the sum variable you declared to itself and the current value of arr[i] - that is:
sum = sum + arr[i] ;

after the loop, you need to return sum.


收錄日期: 2021-05-02 18:17:02
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080504182925AAPpIVu

檢視 Wayback Machine 備份