一、条件判断语句
1、if-else语句
if (条件表达式)
if语句体;
如果条件表达式为true,执行if语句体, 否则不执行。 当if只有一条语句体时,可以省略{},但是,强烈建议, 不管if有几条语句体,都不要省略{}。
/*
if-else
if (条件表达式) {
if语句体;
} else {
else语句体;
}
当条件表达式为true时,执行if语句体。
否则,执行else语句体。
*/
public class IfElse {
public static void main(String[] args) {
int x = -1;
if (x > 0) {
System.out.println("注册成功");
} else {
System.out.println("注册失败");
}
}
}
/*
if (条件表达式1) {
语句1;
} else if(条件表达式2) {
语句2;
} else if (条件表达式3) {
语句3;
} ……
} else if (条件表达式n) {
语句n;
}
从上到下依次判断各个条件表达式,哪一个条件表达式为true,
就执行对应的分支。至多只会执行一个分支。
*/
public class IfElseif {
public static void main(String[] args) {
//当执行多选择分支时,如果多个条件存在包含关系,
//则需要将范围最小的放在最前面,范围大的放在后面。
/*
错误
int score = 90;
if (score >= 60) {
System.out.println("及格");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 90) {
System.out.println("优秀");
}
*/
int score = 90;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
}
/*
当各个条件没有关联,但频率不同的时候,
我们应该将频率高的放在上面,频率低
的放在下面,以减少判断次数。
40 * 1ms + 30 + 2ms + 20 * 3ms + 10 * 4ms
10 * 1ms + 20 * 2ms + 30 * 3ms + 40 * 4ms
*/
int direction = 1;
if (direction == 1) {
System.out.println("向东");
} else if (direction == 2) {
System.out.println("向南");
} else if (direction == 3) {
System.out.println("向西");
} else if (direction == 4) {
System.out.println("向北");
}
}
}
/*
if (条件表达式1) {
语句1;
} else if(条件表达式2) {
语句2;
} else if (条件表达式3) {
语句3;
} ……
} else if (条件表达式n) {
语句n;
} else {
else语句;
}
从上到下依次判断各个条件表达式,哪一个条件表达式为true,
就执行对应的分支。如果所有的条件表达式都为false,则执行
else分支。
*/
public class IfElseifElse {
public static void main(String[] args) {
int score = 90;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
}
}
2、switch case
/*
switch (表达式) {
case 值1: 分支1; [break;]
case 值2: 分支2; [break;]
……
case 值n: 分支n; [break;]
default: 默认分支; [break;]
}
使用表达式的值,依次与每个case进行比较,
哪个case匹配,就执行对应的分支。
如果所有的case都不匹配,则执行default分支。
default分支是可选的。
switch表达式的类型可以是byte,short,int,char,以及
对应的包装类型,String类型与枚举类型。
不可以是boolean,float,double,long。
每个case的值要求是常量值(常量表达式)。
各个case的值不能重复。
*/
public class Switch {
public static void main(String[] args) {
int x = 10;
switch (x) {
case 1: System.out.println("1");break;
case 2: System.out.println("2");break;
case 3: System.out.println("3");break;
default: System.out.println("4");break;
}
switch (x) {
case 1:
case 2: System.out.println("1或2");break;
case 3: System.out.println("3");break;
default: System.out.println("4");break;
}
//switch对String的支持
String s = "abc";
switch (s) {
case "a": System.out.println("1");break;
case "b": System.out.println("2");break;
case "abc":System.out.println("3");break;
}
}
}
原文:http://www.cnblogs.com/liuwei6/p/6561268.html