Tony L Tony L - 3 months ago 12
Java Question

A persistent compilation error when finding the maximum of three integers using java

I'm new to Java and trying to find a solution to a problem that has been returning a persistent compilation error.

I have pasted my code as below:

import java.util.*;

class MaxInteger {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter three integers: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
int max = getMax(num1, num2, num3);

System.out.println("Maximum input integer is " + max);
}

public static int getMax(int num1, int num2, int num3) {
if ((num1 >= num2) && (num1 >= num3))
return num1;
else if ((num2 >= num1) && (num2 >= num3))
return num2;
else if ((num3 >= num1) && (num3 >= num2))
return num3;
}
}


edit: editing this question to make it better after seeing the responses from Jon Skeet, mrt, Jayan et al that this may be viewed as off-topic.


  1. The error message I'm getting is "missing return statement".

  2. I understand that there is a Math.max method of finding the maximum, but in this particular case, the task was given to convert to "if else" statements.

  3. There weren't any missing braces, brackets, and parentheses in my original code. They might have occurred in my copying of the code. Apologies for any confusion.

  4. Thanks to everyone who answered because I learned a lot from all the comments.

  5. Sorry if I phrased this question badly or asked a bad question. It's my 1st question here. I'll try to do better.



"tl;dr" version:
Sorry for any mistakes, omissions or confusion caused by me.
Thanks for the help from all the members.

Answer

Even though you know that this method will always return something, the compiler doesn't. The solution is to make the last else if an else as you know that this will still be logically correct.

public static int getMax(int num1, int num2, int num3) { 
    if ((num1 >= num2) && (num1 >= num3)) 
        return num1;
    else if ((num2 >= num1) && (num2 >= num3)) 
        return num2;
    return num3;
}

And one thing more! You're missing closing bracket of your class which I have added to your code snippet by editing the question as I qualified is as a typo. I assumed that you have it in your original code but I'm not sure now.

The above is about your compilation error. You can find some code review below.

Another thing is DRYing your code. Why should you repeat something that some one has written before? To calculate maximum of three numbers simply return:

public static int maxOfThree(int num1, int num2, int num3) { 
    return Math.max(Math.max(num1,num2),num3);
}