I have this code sample with a method which returns the sum of array values. But instead of the sum, I'm getting 0.
This is my code sample
class Calculation {
int answer;
public int SumOfArrays(int data[], int size) {
answer = 0;
for (int i = data[0]; i < size; i++) {
answer += data[i];
//System.out.println(data[i]);
}
return answer;
}
class Main {
public static void main(String[] args) {
Calculation cal = new Calculation();
int data[]={10,20};
System.out.println(cal.SumOfArrays(data, 2));
}
}
can anyone tell me what;s wrong with my code?
sizeis the array size. without usingdata.lengthI need to set array size manually as a parameter in the method.System.out.println(Arrays.stream(data).sum());Don't reinvent the wheel. And if you must reinvent the wheel, use afor-eachloop.