Reputation: 25
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);
}
}
Upvotes: 0
Views: 228
Reputation: 2137
A good check to find a number is odd is to check if the remainder by dividing the number is not 0 rather then checking if it is 1. The method would look like:
public boolean isOdd(int number) {
return !(number % 2 == 0);
}
Upvotes: 0
Reputation: 2497
It's because negative odd 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;
}
Upvotes: 2