1. public class Spock{
2. public static void main(String[] args){
3. Long tail = 2000L;
4. Long distance = 1999L;
5. Long story = 1000L;
6. if((tail>distance) ^ ((story*2)==tail))
7. System.out.print("1");
8. if((distance+1 != tail) ^ ((story*2)==distance))
9. System.out.print("2");
10. }
11. }
What is the result?[1]
A. 1
B. 2
C. 12
D. Compilation fails.
E. No output is produced.
F. An exception is thrown at runtime.
這個在網站上雖然沒有講解, 但是以我的理解,
因為if的判斷是會以布林運算式判斷, 但是判斷前先執行() 內的運算,
而!=這種等號都會以整數int型態來運算,對於long型態而言,
小數點後的値就算1L-1L也可能會等於0.000000***這種情況出現,
所以第六行(tail>distance) => (2000L>1999L) -> true,
((story*2)==tail) => ((1000L*2)==2000L) -> false,
而true ^ false -> false
[1] http://192.192.246.169/~wells/wiki/index.php/SCJP_1.6%E7%89%88%E8%80%83%E9%A1%8C_008
針對邏輯運算子給自己一點測試吧, 在猛虎的1-9-5(p1-45).
運算子 說明 範例 類別
& AND a&b 雙元
| OR a|b 雙元
! NOT !a 單元
short-circuit Operator
&& AND a&&b 雙元
|| OR a||b 單元
而沒短路的情況之下,判斷是在做完左邊運算後仍會執行右邊運算。
在短路情況下,則是在左邊運算式為false情況下,才會執行右運算。
- - - - -
ex_008_operator.java
public class ex_008_operator{
public static void main(String args[]){
int a = 1, b = 2;
System.out.println((a<b)&&(a>0)); //t && t -> t
System.out.println((a<b)&(a>0)); //t & t -> t
System.out.println((a>b)||(a<0)); //f || f -> f
System.out.println((a>b)|(a<0)); //f | f -> f
System.out.println(!(a>b)); //!f -> t
System.out.println(a); // (1)
if((a<b)|(++a>0))
System.out.println(a--); // (2)
System.out.println(a); // (1)
System.out.println(a&b); //0001 & 0010 -> 0000 (0)
System.out.println(b&b); //0010 & 0010 -> 0000 (2)
System.out.println(a|b); //0001 | 0010 -> 0011 (3)
System.out.println(b|b); //0010 | 0010 -> 0010 (2)
System.out.println(a^a); //0001 ^ 0001 -> 0000 (0)
System.out.println(a^b); //0001 ^ 0010 -> 0011 (3)
System.out.println(a^7); //0001 ^ 0111 -> 0110 (6)
}
}
前面部分為猛虎的範例, 後面是我的測試,
其實主要在" ^ "啦, 因為這啥全忘了,
由側式可以看出來是 XOR, 相異才為1, 相同為0.
另外, 在if裡面運用運算元也是可以改値的.
第六行 true^true->false 所以不印
回覆刪除你說的true^false不是變false而是true......