这 ? (三种方式)运算符 [英] The ? (three way) Operator

查看:60
本文介绍了这 ? (三种方式)运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对以下问题表示歉意,我是java的新手,我从书中摘取了示例,但未能完全说明本身.

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);
    }
}

我了解第一部分如何得出10的结果. 但是我无法理解第二部分如何给出10的结果?

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

很抱歉,这很明显.

推荐答案

条件运算符用于确定要分配给变量的两个值中的哪个.

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

采用以下形式:

type variableName =(布尔条件)? valueIfTrue:valueIfFalse;

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

您的情况是:

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< 0,则i等于-10,因此小于0.因此,指定了真实条件,其值为-i.

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.

由于-(-10)=-*-10 = 10 [即负乘以负加],因此输出为10.

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

这篇关于这 ? (三种方式)运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆