MarcG33 MarcG33 - 21 days ago 5
Java Question

If Else If. Having trouble properly forming a return

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.");
}
}

Answer Source
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";
        }