如果条件为假,是否可以在“if-statement”中执行实际语句?

时间:2017-05-05 19:33:09

标签: java if-statement

我在JavaNotes书中遇到了下面的代码示例。答案是执行后x等于2.

我的问题是这究竟是如何运作的?

我看到它不是if-else流,但是在第二个“if”中boolean表达式为false,因此X不会获得值2。 这是怎么回事?

int x; 
x = -1; 
if (x < 0) 
  x = 1;
if (x >= 0) 
  x = 2;

2 个答案:

答案 0 :(得分:5)

试试animal-sniffer-maven-plugin!阅读代码中的注释,以便了解代码的工作方式:

int x;
x = -1;
if (x < 0) { //-1 < 0 = true
    x = 1;   //enter here -> change x = 1
}//end of the first if

if (x >= 0) {//1 >= 0 = true
    x = 2;   //enter here -> change x = 2
}//end of the second if

System.out.println(x);//result is 2

如果您期望x = 1,那么您的代码应如下所示:

if (x < 0) { //-1 < 0
    x = 1;   //enter here -> change x = 1
} else if (x >= 0) {//1 >= 0
//^^^^------------------------------------------note the else
    x = 2;   //enter here -> change x = 2
}

答案 1 :(得分:1)

x = -1; 首先如果:x&lt; 0是真的, 所以x获得新值1

第二个if:x&gt; 0是真的 所以x获得新值2 x = 2;

相关问题