The issue is that when an integer lesser than or equals to 0 is passed as a parameter for 'end', and when 'end' is lesser than 'start' it doesn't return -1.
public static boolean isOdd (int number)
{
if (number < 0)
{
return false;
}
else
{
if (number % 2 != 0 )
{
return true;
}
else
{
return false;
}
}
}
This is method to test the parameter 'start' and 'end'
public static int sumOdd (int start, int end)
{
int sum = 0;
for (int i = start; i<=end; i++)
{
if ((start<=0) || (end<=0) || (end<start))
{
return -1;
}
else
{
if (isOdd(i))
{
sum+=i;
}
}
}
return sum;
}
The problem lies in your for loop.
You instructed the loop to run when i was smaller or equal to end. That's sounds good on paper, but you do realize that this statement
if ((start<=0) || (end<=0) || (end<start))
will never be run (in the case that end is larger than start), since i is start, and if end is bigger than start, it is therefore bigger than i, which wouldn't satisfy your previous defined condition in the for loop, i is smaller or equal to end. Therefore, the for loop will never run.
You should be doing:
public static int sumOdd(int start, int end) {
int sum = 0;
if ((start <= 0) || (end <= 0) || (end < start)) {
return -1;
} else {
for (int i = start; i <= end; i++) {
if (isOdd(i)) {
sum += i;
}
}
return sum;
}
}
Test Run
sumOdd(1, 0) returns -1
sumOdd(1, 3) returns 4