ndpasu
ndpasu

Reputation: 37

How do i exclude negative numbers in an if loop?

For my project, the user enters a set of numbers, and some calculations are performed to give the desired output. One of the calculations is the find the sum of the odd numbers that are inputted. Looking at the given test cases, I noticed my code was adding the negative odd numbers, while the correct test cases do not. Is there any easy fix for this?

Thanks

Here is some of the code, what I have written minus a few parts.

import java.util.Scanner;

public class Test 
{
public static void main (String[] args)
{
    int min_interger = 0;
    int sum_of_pos = 0;
    int sum_of_odd = 0;
    int count_of_pos = 0;
    int userInput;

    Scanner consoleInput = new Scanner(System.in);

    do {userInput = consoleInput.nextInt();


    if(userInput % 2 != 0)
    {
        sum_of_odd = sum_of_odd + userInput;
    }

    while (userInput != 0);

    System.out.print("The sum of the odd integers is " + sum_of_odd + "\n")
}

}

Upvotes: 2

Views: 1116

Answers (1)

KAD
KAD

Reputation: 11122

Make sure to add odd and greater than zero numbers

if(userInput % 2 != 0 && userInput > 0)
    {
        sum_of_odd = sum_of_odd + userInput;
    }

Upvotes: 4

Related Questions