Resolving “The method must return a result of type int” in Java

后端 未结 9 667
庸人自扰
庸人自扰 2021-01-21 12:37

I\'m very new to Java. Eclipse is giving me the error

The method must return a result of type int

for the following code:



        
9条回答
  •  一向
    一向 (楼主)
    2021-01-21 13:26

    This Eclipse error has already been answered by other users. Anyway here is an alternative to find the largest number of type int

    Alternative - Find the largest integer, using stream():

    public static int largest(int a, int b, int c) {
        return Arrays.asList(a, b, c).stream().max(Integer::compareTo).get().intValue();
    }
    

    Summary of the error:

    Here is the Eclipse error:

    The method must return a result of type int
    

    Reson for error:

    Not all condition are taken care of in method largest. "Outside" condition 'if(a > b)' a "return an int" is needed.

    Alernative - 'if statements' using Clean code's concept 'early return'/'eager return':

    public static int largest(int a, int b, int c) {
        if(a > b && a > c) {
            return a;
        }
    
        if(b > c) {
            return b;
        }
    
        return c;
    }
    

提交回复
热议问题