使用字符串选项优化if-else / switch-case [英] Optimizing if-else /switch-case with string options

查看:178
本文介绍了使用字符串选项优化if-else / switch-case的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码会带来什么修改?在最后几行中,我应该使用更多 if-else 结构,而不是 if-if-if

What modification would bring to this piece of code? In the last lines, should I use more if-else structures, instead of "if-if-if"

if (action.equals("opt1"))
{
    //something
}
else
{
    if (action.equals("opt2"))
    {
        //something
    }
    else
    {
        if ((action.equals("opt3")) || (action.equals("opt4")))
        {
            //something
        }
        if (action.equals("opt5"))
        {
            //something
        }
        if (action.equals("opt6"))
        {
            //something
        }
    }
}

稍后编辑:这是Java。我认为switch-case结构不适用于Strings。

Later This is Java. I don't think that switch-case structure will work with Strings.

稍后编辑2:


开关使用byte,short,
char和int原始数据类型。它
也适用于枚举类型
(在类和继承中讨论)
和一些特殊的类包装
某些原始类型:Character,
Byte, Short和Integer(在简单数据对象中讨论
)。

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).


推荐答案

甚至如果你不使用switch语句,是的,如果要避免无用的比较,请使用else:如果第一个 if 被采用,你不希望所有其他ifs在这里被评估,因为他们将总是假的。此外,您不需要缩进每个如果使最后一个块如此缩进,以至于您无法在不滚动的情况下看到它,以下代码是完全可读的:

Even if you don't use a switch statement, yes, use else if to avoid useless comparison: if the first if is taken, you don't want all others ifs to be evaluated here since they'll always be false. Also you don't need indenting each if making the last block being so indented that you can't see it without scrolling, the following code is perfectly readable:

if (action.equals("opt1")) {
}
else if (action.equals("opt2")) {
}
else if (action.equals("opt3")) {
}
else {
}

这篇关于使用字符串选项优化if-else / switch-case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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