注意:if的判断的条件的结果一定是 bolean 类型。如果条件判断的表达式的返回值是 true,则可以执行 if 内部的语句,反之,就不执行。
语法: if( 条件判断表达式 ){ 执行语句… }else{ 执行语句… }注意:如果条件判断的表达式的返回值是 true,则可以执行 if 内部的语句,反之,就执行 else 中的语句。
语法: if( 条件判断表达式 ){ 执行语句… }else if( 条件判断表达式1 ){ 执行语句… }else if( 条件判断表达式2 ){ … }else{ 执行语句… }注意:多重 if,当遇到满足第一个表达式条件时,执行当前 if 语句,并且不会再向下执行。
注意: case后边的这个常量要和表达式的结果做等值判断,如果判断相等,就执行它下面的语句。在执行 break 的时候跳出 switch;如果一个也没有匹配上,就执行 default 默认情况。 break 可以省略不会报错;但是要知道,如果省略就会穿透执行语句(不管是否能匹配上),直到遇到一个 break 才会跳出,所以一般情况下,我们不建议省略 break。
举个例子:
class Demo1{ public static void main(String[] args){ int dj = 1; switch(dj){ case 1: System.out.println("*"); //break; case 2: System.out.println("**"); //break; case 3: System.out.println("***"); break; case 4: System.out.println("****"); break; case 5: System.out.println("*****"); break; default: System.out.println("请重新输入..."); break; } } } // 因为dj=1,所以输出的结果应该是“*”,但是在这里我们把“case 1”,“case 2”的“break;” 给注释掉了,所以最后的输出结果为:“*” “**” “***”switch 和 if 的区别: if 可以做等值判断,也可以做区间判断;switch 只能做等值判断。
举个例子吧:计算2017年的2月有多少天?
class Demo1{ public static void main(String[] args){ int year = 2017; int month = 2; int day = 0; switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = 31; break; case 4: case 6: case 9: case 11: day = 30; break; case 2: if((year%400) == 0 || (year%4 == 0&& year%100 != 0)){ day = 29; }else{ day = 28; } break; default: System.out.println("一年中没有这个月份"); break; } System.out.println(year + "年"+ month+"月有"+day+"天"); } }注意: switch后边括号内的表达式的类型可以是:byte,short,int,char,string(jdk1.7以后才可以使用string类型);
下面对string类型进行举例说明吧:
class Demo1{ public static void main(String[] args){ String dj = "a"; switch(dj){ case "a": System.out.println("*"); break; case "b": System.out.println("**"); break; case "c": System.out.println("***"); break; case "d": System.out.println("****"); break; case "e": System.out.println("*****"); break; default: System.out.println("请重新输入..."); break; } } } // 输出结果为:*