Java - limit number between min and max

后端 未结 7 706
耶瑟儿~
耶瑟儿~ 2020-12-06 08:53

I want to return the number as long as it falls within a limit, else return the maximum or minimum value of the limit. I can do this with a combination of Math.min

相关标签:
7条回答
  • 2020-12-06 09:38

    The Math.max(int a, int b) function is defined as:

    public static int min(int a, int b) {
        return (a <= b) ? a : b;
    }
    

    So you can make a combination of the max and min functions as follows:

    private static int MAX=10;
    private static int MIN=0;
    
    public int limit(int a) {
        return (a > MAX) ? MAX : (a < MIN ? MIN: a );
    }
    
    0 讨论(0)
提交回复
热议问题