-1

I get an error message saying:

This method must return a result of type int.

My code:

public int countOdds (int[] values) {
  int countOdd =0;
  for (int i=0; i<values.length; i++) {
    if (values[i] %2 != 0) {
      countOdd++;
      return countOdd;
    }
  }
}

4 Answers 4

5

The following line

return countOdd;

should be outside of your for-loop.

Otherwise, you'll either return 1 when you reach the first odd, or you won't reach a return statement at all if there are no odds.

public int countOdds (int[] values) {
  int countOdd =0;
  for (int i=0; i<values.length; i++) {
    if (values[i] %2 != 0) {
      countOdd++;
    }
  }
  return countOdd;
}
5

Compiler thinks that the method may not return anything at all:

public int countOdds (int[] values) {
  int countOdd =0;
  for (int i=0; i<values.length; i++) {
    if (values[i] %2 != 0){
      countOdd++;
      return countOdd;
    }
  }
  // what if this line is reached?
}

Suppose you run it with values.length = 0. What will the method return?

Your return statement should be in a different place in code

1
  • Or if all items in values are even?
    – chepner
    Apr 29, 2013 at 22:10
1

If the values array has no odd numbers in it, then your function exits without returning an int. As noted in a previous answer, move the return statement out of the loop.

Also, because the value of values[i]%2 is 0 for even numbers and 1 for odd numbers, the number of odd numbers is equal to the sum over i of values[i]%2, allowing you to significantly shorten the code:

public int countOdds (int[] values) {
  int i, count=0;
  for (i=0; i<values.length; ++i) {
    count += values[i]%2;
  }
  return count;
}

An alternative version uses bitwise AND:

 public int countOdds (int[] values) {
  int i, count=0;
  for (i=0; i<values.length; ++i) {
    count += values[i] & 1;
  }
  return count;
}
-1

Supposing the if-statement never returns true, will the method return anything? No, it won't, so you need to include a return statement that will execute in the event the if-statement never runs.

  public int countOdds (int[] values) {
  int countOdd =0;
  for (int i=0; i<values.length; i++) {
    if (values[i] %2 != 0) {
      countOdd++;
    }
  }
  return countOdd;
}
2
  • 1
    No reason include the magic number 0; it's just a matter of moving the variable down to return instead of a number.
    – Makoto
    Apr 29, 2013 at 22:29
  • This method returns zero or one only. -1
    – user207421
    Apr 30, 2013 at 1:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.