The ? (three way) Operator

落花浮王杯 提交于 2019-12-11 11:56:43

问题


First of all, apologies for the following question, i am new to java, i have taken the example from a book but it fails to completely explain itself.

I have been reading about the ? operator and how it functions and using the below as an example to learn from:

class Ternary {
    public static void main(String args[]) {
        int i, k;
        i = 10;
        k = i < 0 ? -i : i; // get absolute value of i
        System.out.print("Absolute value of ");
        System.out.println(i + " is " + k);

        i = -10
        k = i < 0 ? -i : i; //get absolute value of i
        System.out.print("Absolute value of ");
        System.out.println(i + " is " + k);
    }
}

I understand how the first part gives the result of 10. But i cannot follow how the second part gives the result of 10?

Apologies if this is plainly obvious.


回答1:


The conditional operator is used to decide which of two values to assign to a variable.

It takes the form:

type variableName = (boolean condition) ? valueIfTrue : valueIfFalse;

In your case you have:

public static void main(String[] args){
    int i, k;
    i = -10;
    k = i < 0 ? -i : i; //get absolute value of i
    System.out.print("Absolute value of ");
    System.out.println(i + " is " + k);
}

So, we are saying:

i < 0, well i is equal to -10 and is therefore less than 0. therefore the true condition is assigned, which has the value of -i.

Since -(-10) = -*-10 = 10 [i.e minus times minus is plus], the output is 10.




回答2:


Since the ternary operator evaluates i < 0 in your following line of code:

k = i < 0 ? -i : i; //get absolute value of i

If true k = -i

else false k = i

And as the others mentionned, -(-10) == 10 And I believe this is the output you want since you are trying to get the absolute value of a number, so if it is negative, print out it's positive value.




回答3:


A negative of a negative is a positive 0 - (-10) = 10




回答4:


when setting k, we have the condition

i < 0

followed by the ?, which asks "Is i less than 0. If it is, it will return the first result (-i), and if it is not it will return the second result (i).

It means the same thing as:

if (i < 0){
    k = -i;
else{
    k = i;
}



回答5:


i = -10
k = i < 0 ? -i : i; 

is the same as

k = i < 0 ? -(-10) : i;

gives you +10




回答6:


When you write:

k = i < 0 ? -i : i

it's interpreted as

if(i < 0){
    k = -i;
} else {
    k = i;
}

So since -10 is < 0, the given expression returns -(-10), that is 10




回答7:


i gets set to -10 and then k checks if i < 0, which it is.

Therefore it performs the first case:

k = -(-10) = 10



来源:https://stackoverflow.com/questions/29676600/the-three-way-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!