# Java實用但不確定簡不簡單的教學 Day-3 --- ## 布林邏輯 用數學來說明,其實就是集合的意思 而在電腦科學裡就是true代表真 而false代表假 ```java true false ``` 符號 |代表意思 -----|-------- && | and 代表"與" \|\| | or 代表"或" \! | not 代表"非" ---- 在電腦裡,我們也可以用1與0分別代表true與false --- ## 條件判斷式 在程式語言中,我們能利用條件判斷式來決定一段程式碼是否要執行 而在Java中的語法如下 ```java int x=10; if(x==5){ System.out.println("x是5!");//不會執行 } ``` 判斷符號|意思 -------|--- == |是否等於對方 > |是否大於對方 < |是否小於對方 >= |是否大於等於對方 <= |是否小於等於對方 當條件符合的時候,判斷式便會輸出為true,否則會輸出false 而只有當判斷式為true的時候,if裡面的程式區塊才會執行 ---- ### if...else 上面說過我們可以利用if來作條件判斷,而我們也可以讓他條件不符合的時候執行其他的程式,如下列範例 ```java String skill="日蝕"; if(skill=="星爆氣流斬"){ System.out.println("10秒16連擊!");//不會執行 }else{ System.out.println("這什麼到底什麼招式?");//會執行 } ``` 又或著你需要判斷多個東西,則可以用if else ```java String player="Asuna"; if(player=="Kirito"){ System.out.println("Stay Cool"); }else if(player=="Asuna"){ System.out.println("那到底是什麼招式阿");//只會執行這個 }else if(player=="Heathcliff"){ System.out.println("這不是很戲劇化的發展嗎?"); }else{ System.out.println("其實你是牙王對吧?"); } ``` ---- ### switch...case if else如果東西太多的話,就會變得很複雜,很難看懂 尤其是像我們只是要簡單判斷player這個變數是否等於這些玩家的時候 這種簡單的判斷式我們便可以使用switch...case來代替 不僅閱讀性變高,也不用寫那麼多東西 我們來把上面的改寫 ```java String player="Asuna"; switch (player){ case "Kirito": System.out.println("Stay Cool"); break; case "Asuna": System.out.println("那到底是什麼招式阿");//只會執行這個 break; case "Heathcliff": System.out.println("這不是很戲劇化的發展嗎?"); break; default: System.out.println("其實你是牙王對吧?"); } ``` 而如果要用在switch...case裡使用or的話 則必須這樣打 ```java String player="Kirito"; switch (player){ case "Kirito": case "黑衣劍士": System.out.println("今天很星爆是吧"); } ``` 不過可惜的是如果判斷式太複雜的話,switch...case是無法使用的
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up