rls1982 rls1982 - 1 year ago 140
Java Question

Return sum of Positive Number

I'm having to write a program in which method returns the sum of the positive numbers read , and will read the input from the user until zero is entered.

What I have so far is not calculating the sum of the positive numbers entered and I need some help please.

Here is what I have so far:

(notice you're given the Scanner, do not use System.in) -
reads from user until given 0 and returns sum of the positive numbers read.


♦ user enters: 0 => return 0

♦ user enters 1 2 3 0 => returns 6 (1+2+3)

♦ user enters 1 -2 3 0 => returns 6 (1+3, skip -2 since it is negative)

public static int readAndSumPositives(Scanner in,PrintStream out)
int input;
int count;
int sum;
int total;

sum = 0;
count =0;
total = sum+count;

out.println("Please enter a number");
while(input != 0 && input != -2 && input != -3 && input != -4) {
sum += input;
out.println("Enter your next positive number");

if (input == 0) {
return sum;
} else return input;

Here is the code that is executing when I run this method in GitBash

private static int readAndSumPositivesFrom(String input) {

ByteArrayOutputStream out_bs = new ByteArrayOutputStream();
PrintStream out=new PrintStream(out_bs);

Scanner in_s = new Scanner(new ByteArrayInputStream(input.getBytes()));
int ans = Assignment5.readAndSumPositives(in_s,out);
return ans;

@Grade(points = 20)
public void testReadAndSumPositives() {
Assert.assertEquals(30, readAndSumPositivesFrom("10 20 0 "));
Assert.assertEquals(20, readAndSumPositivesFrom("10 -20 10 0 "));
Assert.assertEquals(10, readAndSumPositivesFrom("1 2 -2 3 -3 4 -4 0 "));

Any help is appreciated and points will be awarded!

Thanks in advance.

Answer Source

You are returning wrong values. You should return input when the first input is 0 and sum when it is not. You are doing just the opposite. Also, taking the first input outside the loop and then checking it in the loop and taking the next input in the loop is bound to cause a logical error if the user enters a positive number in the first place (or rather a syntax error since input is not initialized outside the loop). Do everything inside the loop and check what you are returning.

while(true){  //infinite loop
    out.println("Enter positive number to add, 0 to stop.");
    input = in.nextInt();
    if(input == 0)
    if(input > 0)
        sum+= input;
return sum;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download