文章目錄
Java 支援數學中常見的邏輯條件:
- 小于:a < b
- 小于或等于:a <= b
- 大于:a > b
- 大于或等于:a >= b
- 等于a == b
- 不等于:a != b
Java 有以下條件語句:
- 使用if指定的代碼塊将被執行,如果一個指定的條件是真
- 使用else指定的代碼塊将被執行,如果相同的條件為假
- 使用else if指定一個新的條件測試,如果第一個條件為假
- 使用switch指定的代碼許多替代塊被執行
我們測試兩個值以找出 10是否大于 8。如果條件為true,則列印一些文本:
package test8;
public class test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
if (10 > 8) {
System.out.println("10大于8");
}
}
}
運作:
或者你也可以這樣:
package test8;
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x大于 y");
}
}
}
在上面的示例中,我們使用兩個變量x和y來測試 x 是否大于 y(使用>運算符)。由于 x 是 10,y 是 8,并且我們知道 10 大于 8,是以我們在螢幕上列印“x 大于 y”。
當if前面的語句非真的時候,我們就執行else語句。舉個例子:
package test8;
public class test3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int time = 20;
if (time < 18) {
System.out.println("成功.");
} else {
System.out.println("失敗.");
}
}
}
如果20小于18才執行if語句,是以我們隻能執行else語句。
簡單點說就是if語句非真,那麼就執行else if,else if是并列的按順序的,else if都為假,則執行else.
package test8;
public class test4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int time = 22;
if (time < 10) {
System.out.println("川川");
} else if (time < 20) {
System.out.println("菜鳥.");
} else {
System.out.println("川川菜鳥.");
}
}
}
因為前面都為假,隻能執行else.
如果前面你學得比較好,那麼你一定能懂這部分代碼:
package test8;
public class test5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int time = 20;
if (time < 18) {
System.out.println("川川.");
} else {
System.out.println("菜鳥.");
}
}
}
那麼我們換一下新的方式來表達:
package test8;
public class test6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int time = 20;
String result = (time < 18) ? "川川" : "菜鳥";
System.out.println(result);
}
}
你可以看到這裡就變換成了簡單的一句話。細細品味一下。