简体   繁体   中英

Can an IF statement be used inside math.max in Java?

I want to know if it is possible to use an if statement inside of math.max. For example if you have an object like so:

    public class Obj {
        private int i;
        private boolean b;
        public void setInt(int newInt) {
            this.i = newInt;
        }
        public void setBool(boolean newBool) {
            this.b = newBool;
        }
        public int getInt() {
            return this.i;
        }
        public boolean getIsTrue() {
            return this.b;
        }
    }

After initializing 2 new objects and defining all values, is it possible to do something like this:

    System.out.println(Math.max(if(obj1.getIsTrue()) {obj1.getInt()}, if (obj2.getIsTrue()) {obj2.getInt()}));

I know that it can be done with an array and a for loop, so I'm not asking is it possible at all, just is it possible to nest if statements in this way.

An if in Java is a statement and not an expression , and that means that it doesn't return a value. What you can use is a conditional expression (also known as the ternary operator), as long as you can provide a meaningful else part:

Math.max(obj1.getIsTrue() ? obj1.getInt() : 0, obj2.getIsTrue() ? obj2.getInt() : 0);

Also notice that Math.max() receives only 2 arguments, not 3 as you seem to expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM