-1

I am at a dead end with this assignment. Looking at it, I feel that everything is good with the brackets and the if else statements. However, the error says "missing return statement }"
_____________________________________________________________________^

public class CompareNums {
    // TODO - write your code below this comment.
    // The method you define will return one of three possible strings:
    // - "less than": if the first parameter is less than the second
    // - "equal to": if the first parameter is equal to the second
    // - "greater than": if the first parameter is greater than the second
    // Make sure you return _exactly_ the above strings
    public static String comparison(int first, int second) {
        if (first<second) {
            return "less than"; 
        } else if (first==second) {
            return "equal to"; 
        } else if (first>second) {
            return "greater than";
        }
    }



    // DO NOT MODIFY main!
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter first integer: ");
        int first = input.nextInt();
        System.out.print("Enter second integer: ");
        int second = input.nextInt();
        System.out.println("The first integer is " +
                           comparison(first, second) +
                           " the second integer.");
    }
}
MarcG33
  • 7
  • 4

2 Answers2

1

You need to end if statements with an else if you are using a return inside the function. The error is basically saying what if none of those conditions are met, something still needs to be returned. Using your example you could say this instead:

 public static String comparison(int first, int second) {
        if (first<second) {
            return "less than"; 
        } else if (first>second) {
            return "greater than";
        } else {
            return "equal to";
        }
    }

You can assume that if the first is not less than or greater than the second it is therefore equal to.

0
if (first<second) {
            return "less than"; 
        } else if (first==second) {
            return "equal to"; 
        } else if (first>second) {
            return "greater than";
        }

the last else if is redundant and is the actual cause of the problem. naturally if the above 2 conditions are false then first will be greater than second.just use else instead of else if.

if (first<second) {
            return "less than"; 
        } else if (first==second) {
            return "equal to"; 
        } else  {
            return "greater than";
        }
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24