Odd sum application not calculating negative integers correctly?

1686 views java
4

I'm supposed to create an application that takes a number from the user in order to create a range from 1 to the number that the user enters. I then need to calculate the sum of all odd numbers between 1 and the number that the user enters. This works fine with positive integers but not with negative?

import java.util.Scanner;
public class OddSumApplication {
public static void main (String[]args){

    int sum = 0;

    System.out.print("Enter a positive or negative integer: ");
    Scanner in = new Scanner(System.in);
    int num = in.nextInt();

    if (num == 1){
        System.out.println(num);
        System.out.println("Sum = " + num);
    }
    else{
        while (num != 1){
            if (num >= 1){
                if (num % 2 == 1){
                    sum = sum + num;
                    num = num - 2;
                }
                else{
                    num = num - 1;
                }
            }
            else{
                if (num % 2 == 1){
                    sum = sum + num;
                    num = num + 2;
                }
                else{
                    num = num + 1;
                }
            }
        }
    }
        sum = sum + 1;
        System.out.print("\nSum = " + sum);
}

}

answered question

Use the absolute value of num and then you do not need if (num >= 1){...} else {...} block.

1 Answer

6

It's because negative number % 2 returns negative one. Try to give it into absolute value.

...
if (Math.abs(num%2) == 1) {
         sum = sum + num;
         num = num + 2;
     } else {
         num = num + 1;
}

posted this

Have an answer?

JD

Please login first before posting an answer.