0

我已经看到可以使用多个三元条件,但是如果单个条件为真,还没有找到分配两个变量的方法。这是我正在尝试编写的方法:

    int[] chkNext(int mnd, int y) {  
        int[] date = new int[2];  
        mnd = 12 ? mnd = 1, y++ : mnd++; // returns the following: "error: : expected"
        date[0] = mnd, date[1] = y;  
        return date;  
    }  
4

2 回答 2

8

只需使用一个if语句。

if (mnd == 12) {
//      ^^  very important
  mnd = 1;
  y++;
} else {
  mnd++;
}

和这个:

date[0] = mnd, date[1] = y;  

会更好:

date[0] = mnd; date[1] = y;  

如果您真的不需要逗号,请不要使用它。

于 2011-10-31T05:50:40.457 回答
-3

The construct of ternary operator is wrong as there should be condition before '?'. As Mat suggested better option is using if statement.

Ternary can be generally used for simple statements like

boolean isEven = (n!=0 && n%2 == 0) ? true : false;
于 2011-10-31T06:01:29.677 回答