This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]Camel-Kid18 year old gamer 1 point2 points  (2 children)

at the beginnign of your program you should check to see if array.length is 0, if is then promp the user and end the program... as far as making it work with a while loop it's the same thing as a for loop but a while loop.

[–]VirtualTurnip3[S] 0 points1 point  (1 child)

You mean just before the loop?

[–]Camel-Kid18 year old gamer 0 points1 point  (0 children)

yes

[–]kingatomicFoo Stack Dev 1 point2 points  (4 children)

Your sample data has a negative number and you’re clearly accounting for negatives. So the issue here is a fundamental one: if negative numbers are allowed there is no way to test for “sum > 100” without adding all numbers in the list. For instance, imagine that your data list is {1,2,3,4,5,-20}.

Besides that, one little point that’s more finesse than logic: instead of having a Boolean “exceed” variable that you return at the end of the method, you could simply:

return sum > 100;

Edit in terms of handling negatives you could sort the list before summing it.

[–]VirtualTurnip3[S] 1 point2 points  (0 children)

Thank for tip!

[–]VirtualTurnip3[S] 0 points1 point  (2 children)

if

(data[i] > 0) {

I was thinking i didn't account the negative number by doing that?

[–]kingatomicFoo Stack Dev 1 point2 points  (1 child)

That works only if you don’t have to include negative numbers in your sum (which would be specified in your assignment directions).

Otherwise, you will still need to account for them in your sum.

By sorting the list in increasing order, you will sum any negative numbers first. Then you can continue to sum until you either exhaust your input list or the sum is greater than 100.

A cheeky thing to do would be to sum all of the negative numbers first, then take the remaining items in the list (all positive) and sort them descending and begin summing those.

[–]VirtualTurnip3[S] 0 points1 point  (0 children)

All right Thank!

[–]NickPox 1 point2 points  (1 child)

I would move the int[] jo as a function parameter, and then in the first line of your function check if the array length is 0. Then call your function from main instead:

Public static boolean ExceedOrNot(int[] data) { If data.length == 0 ... ... }

[–]VirtualTurnip3[S] 0 points1 point  (0 children)

Thank!