嵌套if-else vs if-else?

时间:2015-11-20 02:09:22

标签: if-statement language-agnostic nested

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

以下问题要求使用它而不是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

2 个答案:

答案 0 :(得分:1)

嵌套if / else表示heirachy所以..

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

答案 1 :(得分:1)

nested if statement基本上是一系列的if statements,就像这样......

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

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

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