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

后端 未结 9 665
庸人自扰
庸人自扰 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:22

    For your second error, the logic seems to be off a little... there is no return statement in the case where b > a.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-01-21 13:26

    During compilation time, your compiler cannot find the parallel else condition of (a>b) that is => if(a<=b)

    what it will return if your input matches this block? So you should provide this

    0 讨论(0)
提交回复
热议问题