Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

"tl;dr" version: Sorry for any mistakes, omissions or confusion caused by me.

like image 660
Tony L Avatar asked Jan 06 '23 10:01

Tony L


2 Answers

Math.max() returns the highest from two values. you can apply this operation twice to get max out of three

int max =  Math.max(Math.max(num1,num2),num3);
like image 135
Amy Avatar answered Jan 13 '23 08:01

Amy


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);
}
like image 41
xenteros Avatar answered Jan 13 '23 09:01

xenteros