形成天才的决定因素应该是勤奋。……有几分勤学苦练是成正比例的, —— 郭沫若
本讲内容:if-else条件语句、switch条件语句
一、if-else条件语句
public class text {
public static void main(String[] args) {
int score=88;
if(score>=90){
System.out.println("优秀");
}else if(score>=80){
System.out.println("良好");
}else if(score>=60){
System.out.println("中等");
}else{
System.out.println("差");
}
}
}
if-else语句规则:
1、if后的括号不能省略,括号里表达式的值最终必须返回的是布尔值
2、如果条件体内只有一条语句需要执行,那么if后面的大括号可以省略,但这是一种极为不好的编程习惯。
3、对于给定的if,else语句是可选的,else if 语句也是可选的
4、else和else if同时出现时,else必须出现在else if 之后
5、如果有多条else if语句同时出现,那么如果有一条else if语句的表达式测试成功,那么会忽略掉其他所有else if和else分支。
6、如果出现多个if,只有一个else的情形,else子句归属于最内层的if语句
二switch分支控制语句 (从简洁程度和效率上,switch都略胜一筹)
public class text {
public static void main(String[] args) {
int month = 9;
switch (month) {
case 1:
System.out.println(month + "月有31天");
break;
case 2:
System.out.println(month + "月有28天");
break;
case 3:
System.out.println(month + "月有31天");
break;
case 4:
System.out.println(month + "月有30天");
break;
case 5:
System.out.println(month + "月有31天");
break;
case 6:
System.out.println(month + "月有30天");
break;
case 7:
System.out.println(month + "月有31天");
break;
case 8:
System.out.println(month + "月有31天");
break;
case 9:
System.out.println(month + "月有30天");
break;
case 10:
System.out.println(month + "月有31天");
break;
case 11:
System.out.println(month + "月有30天");
break;
case 12:
System.out.println(month + "月有31天");
break;
default:
System.out.println("没有这个月份吧");
break;
}
}
}
1、switch表达式必须能被求值成char byte short int 或 enum
记忆的话可以记忆成非lang整形加枚举。请切记在java 6 及以前版本中string是不允许用在switch表达式中的(Java 7可以用string,现在正式版还没出来)
2、case常量必须是编译时常量,因为case的参数必须在编译时解析,也就是说必须是字面量或者是在声明时就赋值的final变量。
public class text {
public static void main(String[] args) {
final int a = 2;
final int b;
b = 3;
int x = 2;
switch (x) {
case 1: // 编译OK
case a: // 编译OK
case b: // 无法通过编译
}
}
}
3、多个case常量重复也会出错:
public class text {
public static void main(String[] args) {
byte x = 2;
switch (x) {
case 1: // 编译OK
case 1:
}
}
}
4、case常量被会转换成switch表达式的类型,如果类型不匹配也会出错:
public class text {
public static void main(String[] args) {
byte x = 2;
switch (x) {
case 1: // 编译OK
case 128: // 无法自动转换成byte,编译器会报错
}
}
}
本讲就到这里,Take your time and enjoy it