简体   繁体   English

可以在Java的math.max内部使用IF语句吗?

[英]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. 我想知道是否可以在math.max中使用if语句。 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: 初始化2个新对象并定义所有值后,可以执行以下操作:

    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. 我知道这可以通过数组和for循环来完成,所以我不问这有没有可能,只是是否可以以这种方式嵌套if语句。

An if in Java is a statement and not an expression , and that means that it doesn't return a value. Java中的if是一个语句而不是一个表达式 ,这意味着它不返回值。 What you can use is a conditional expression (also known as the ternary operator), as long as you can provide a meaningful else part: 只要可以提供有意义的else部分, 就可以使用条件表达式(也称为三元运算符):

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. 还要注意, Math.max()仅接收2个参数,而不是您期望的3个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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