【问题标题】:Nested if-else vs if-else?嵌套 if-else 与 if-else?
【发布时间】:2015-11-20 10:29:15
【问题描述】:

与 if-else if 语句相比,我对“嵌套 if-else 语句”的含义感到困惑。

以下问题要求使用它而不是 if-else 语句,但我不知道如何使用。非常感谢您的帮助!

       if (playerThrow == ROCK && computerThrow == ROCK) {
       System.out.println("Its a draw!");
   } else if (playerThrow == ROCK && computerThrow == PAPER) {
       System.out.println("Computer wins!");
   } else if (playerThrow == ROCK && computerThrow == SCISSORS) {
       System.out.println("Player wins!");

Code is from my textbook (I messed up), else I would have posted mine, sorry

【问题讨论】:

  • 这是一个菜鸟问题
  • 曾经@Drew 我们都是菜鸟...
  • 嗨,欢迎来到 SO!你能稍微编辑一下你的问题吗?我们(大部分时间)接受“codn-mages”。请直接写到问题中。此外,链接可能会随着时间的推移而中断,因此最好仅将它们用作参考。无论如何,我们在这里为您提供帮助;)。
  • @KemyLand 我会感谢你的
  • @Drew:呵呵,我写的是“codn-mages”,但它是“code-images”...

标签: if-statement language-agnostic nested


【解决方案1】:

nested if statement 本质上是一系列相互之间的if statements,就像这样......

if (<condition>)
{
    if (<condition>)
    {
       ...
    } else {
       ...
    }
} else {
    ...
}

If-else if statements 使使用多个条件更清晰、更易于阅读,所有条件都在同一级别,如下所示:

if (<condition 1>)
{
    ...
}
else if (<condition 2>)
{
    ...
}
else
{
    ...
}

【讨论】:

    【解决方案2】:

    嵌套的 if/else 意味着一个 heirachy so..

    if($something == true){
        if($something_else == true){
        } else {
        }
    } else { // $something == false
        if($something_else == true){
        } else {
        }
    }
    

    【讨论】:

    • 我不是反对者,但是...不是 OP 的 Java 代码吗?
    • 那就是零区别,嵌套就是嵌套不管语言,过程都是一样的。语法也类似。
    • @DanWhite 废话抱歉不小心点击了它
    • @DanWhite 感谢您的帮助,等到 6 分钟后我就解决了
    • @Drew 太棒了!很高兴它有帮助(即使它是 Java)!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2012-10-14
    • 1970-01-01
    • 2011-02-24
    • 2021-12-18
    • 2015-06-04
    • 2010-12-17
    相关资源
    最近更新 更多