三元运算符如何工作? [英] How ternary operator works?

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

问题描述

在代码战中,我使用15行代码的for循环完成了kata,其他人仅用7行完成了它。有人可以解释代码吗?

In codewars I have completed a kata using for loop with 15 lines of code, some other person has completed it with just 7 lines. Could anybody explain the code?

public class CamelCase {
    public static String cAmEl(final String yourName) {
        final int length = yourName.length();
        final StringBuilder cAmEl = new StringBuilder(length);
        boolean upper = true;
        for (int i = 0; i < length; i++, upper ^= true) {
            final char c = yourName.charAt(i);
            cAmEl.append(upper ? toUpperCase(c) : toLowerCase(c));
        }
        return cAmEl.toString();
    }
}

该代码将字符串的每个备用字符转换为大写(以大写字母开头)。例如: test 变为 TeSt

The code converts every alternate character of a string to uppercase (starting with an uppercase character). For example: test becomes TeSt.

我是无法理解这部分

cAmEl.append(upper ? toUpperCase(c) : toLowerCase(c));


推荐答案

您不了解的部分是三元的。
三元包含三个部分。
第一部分:条件

The part you don't understand is a ternary. Ternary contains of three parts. part one: Condition

upper

第二部分:真实语句

toUpperCase(c)

第三部分:虚假陈述

toLowerCase(c)

正如您在for语句中所看到的,对字面值进行XOR

As you can see in for statement upper will be XOR to literal value true.

for (int i = 0; i < length; i++, upper ^= true)

因此,在每个迭代中,上位变量的for语句值将是相反的,因此三元数的true语句和false语句将是

So in each iterate of the for statement value of upper variable will be reverse, so true statement and false statement in ternary will be called.

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

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