形成天才的决定因素应该是勤奋。……有几分勤学苦练是成正比例的, —— 郭沫若
本讲内容: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("差");
}
}
}
二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 或 enum2、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,编译器会报错
}
}
}原文:http://blog.csdn.net/liguojin1230/article/details/41280549