执行 SimpleIsland class 中的以下 myProgram() 方法时会打印什么?
What is printed when the following myProgram() method in the SimpleIsland class is executed?
虽然我知道 if/else 语句和运算符是如何工作的(有很多关于它的帖子),但我似乎特别迷失在这段代码中。我得到了最终输出(if else if),但是我无法通过简单地查看它并在纸上计算得出该结论。对于代码中发生的事情的简单解释,我真的很感激。
public class SimpleIsland
{
public boolean getTrue()
{
return true;
}
public boolean getFalse()
{
return false;
}
public static void myProgram()
{
if ( getFalse() || getTrue() )
{
if ( !getTrue() )
{
if ( !getFalse() )
{
System.out.println( "if if if" );
}
else
{
System.out.println( "if if else" );
}
}
else
{
if ( !getFalse() )
{
System.out.println( "if else if" );
}
else
{
System.out.println( "if else else" );
}
}
else
{
System.out.println( "else" );
}
}
}
它将打印'if else if'。第一个 if(getFalse() || getTrue()) 将 return 为真,因为我们正在检查 OR 条件。因此,在输入第一个 if 后,下一个嵌套的 if(!getTrue()) 将 return false,因此控制将移至 else 条件。接下来嵌套在 else 中的 if(!getFalse()) 将评估为 true,因此打印 'if else if'
用值 true 和 false 替换那些 functions 和 nots ,事情会变得更清楚。请永远不要写那样的代码。它会让你和任何必须保持它疯狂的人。
public class SimpleIsland
{
public boolean getTrue()
{
return true;
}
public boolean getFalse()
{
return false;
}
public static void myProgram()
{
if ( false || true )
{
if ( false )
{
if ( true )
{
System.out.println( "if if if" );
}
else
{
System.out.println( "if if else" );
}
}
else
{
if ( true )
{
System.out.println( "if else if" );
}
else
{
System.out.println( "if else else" );
}
}
else
{
System.out.println( "else" );
}
}
}
虽然我知道 if/else 语句和运算符是如何工作的(有很多关于它的帖子),但我似乎特别迷失在这段代码中。我得到了最终输出(if else if),但是我无法通过简单地查看它并在纸上计算得出该结论。对于代码中发生的事情的简单解释,我真的很感激。
public class SimpleIsland
{
public boolean getTrue()
{
return true;
}
public boolean getFalse()
{
return false;
}
public static void myProgram()
{
if ( getFalse() || getTrue() )
{
if ( !getTrue() )
{
if ( !getFalse() )
{
System.out.println( "if if if" );
}
else
{
System.out.println( "if if else" );
}
}
else
{
if ( !getFalse() )
{
System.out.println( "if else if" );
}
else
{
System.out.println( "if else else" );
}
}
else
{
System.out.println( "else" );
}
}
}
它将打印'if else if'。第一个 if(getFalse() || getTrue()) 将 return 为真,因为我们正在检查 OR 条件。因此,在输入第一个 if 后,下一个嵌套的 if(!getTrue()) 将 return false,因此控制将移至 else 条件。接下来嵌套在 else 中的 if(!getFalse()) 将评估为 true,因此打印 'if else if'
用值 true 和 false 替换那些 functions 和 nots ,事情会变得更清楚。请永远不要写那样的代码。它会让你和任何必须保持它疯狂的人。
public class SimpleIsland
{
public boolean getTrue()
{
return true;
}
public boolean getFalse()
{
return false;
}
public static void myProgram()
{
if ( false || true )
{
if ( false )
{
if ( true )
{
System.out.println( "if if if" );
}
else
{
System.out.println( "if if else" );
}
}
else
{
if ( true )
{
System.out.println( "if else if" );
}
else
{
System.out.println( "if else else" );
}
}
else
{
System.out.println( "else" );
}
}
}