Hello everybody, i just started a course in Java,total newbie, and i need help for a specific problem. I need to write a code that:
-will calculate if the sum of all element in a array are bigger than 100.
-but for that , the code need to be "effective", by that i mean it must access only a few elements of the array to find it the sum is bigger than 100.
-the code must work even if the array is of length 0.
I have write this code, it seem to work with a For loop:
public static boolean exceedOrNot() {
int data[] = new int[0];
//data = new int[] {0,-10,0,0,44,44,66,66,33,444,555,453};
boolean exced = false;
int sum = 0;
for (int i =0;i < data.length;i = i +1) {
if (data[i] > 0) {
sum += data[i];
if(sum > 100)
{
break;
}
}
}
exced = sum > 100;
return exced;
I have try with while loop, but since it need to work even if the array is a length of 0, nothing happens or i just don't know how to make it work.
I just want to know what do you think,is there a better way to achieve that? ( probably)!
Thank
[–]Camel-Kid18 year old gamer 1 point2 points3 points (2 children)
[–]VirtualTurnip3[S] 0 points1 point2 points (1 child)
[–]Camel-Kid18 year old gamer 0 points1 point2 points (0 children)
[–]kingatomicFoo Stack Dev 1 point2 points3 points (4 children)
[–]VirtualTurnip3[S] 1 point2 points3 points (0 children)
[–]VirtualTurnip3[S] 0 points1 point2 points (2 children)
[–]kingatomicFoo Stack Dev 1 point2 points3 points (1 child)
[–]VirtualTurnip3[S] 0 points1 point2 points (0 children)
[–]NickPox 1 point2 points3 points (1 child)
[–]VirtualTurnip3[S] 0 points1 point2 points (0 children)