条件分支结构选择
1.if条件结构分支语句:
语法结构:
if(布尔条件表达式){执行语句}
public class Selection {
public static void main(String[] args) {
int x = 520, y = 250;
if (x>y){
System.out.println("520");
}
}
}
执行规则:如果条件表达式为true,就执行花括号里的语句,否则就不执行。
if(布尔条件表达式){语句1}else{语句2}
public class Selection {
public static void main(String[] args) {
int x = 520, y = 250;
if (x<y){
System.out.println("520");
}else {
System.out.println("250");
}
}
}
执行规则:如果条件表达式为true就执行语句1,否则就执行else下的语句。
if(条件表达式1){语句1}else if(条件表达式2){语句2}else{语句n}//注意else if语句可以继续嵌入。
public class Selection {
public static void main(String[] args) {
//键盘扫描器,捕获键盘录入的数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入成绩查看评分祝福语");
int cj = sc.nextInt();
if (cj >= 90){
System.out.println("十年苦读见成效,梦想实现在今朝");
}else if (cj<=89 && cj>=60){
System.out.println("要想飞,就得追;要成功,努力干");
}else if (cj >=0 && cj <= 59){
System.out.println("不为失败找理由,要为成功找方法");
}else {
System.out.println("对不起你输入的成绩无效");
}
}
}
执行规则:如果条件表达式为true,就执行该语句,如果条件表达式都为false,就执行else语句。
2.switch多条件分支语句
语法结构:switch(常量值){
case 值1:
语句1
break;
case 值2:
语句2
break;
default:
语句n
break;
}
public class Selection {
public static void main(String[] args) {
System.out.println("如果要你在以下选择中选择你会选择什么?");
//键盘扫描器,捕获键盘录入的数据
Scanner s =new Scanner(System.in);
System.out.println("1:美女");
System.out.println("2:金钱");
System.out.println("3:权力");
System.out.println("你的选择是:");
String xz = s.next();
switch (xz){
case "我的选择是1":
System.out.println("美女");
break;
case "我的选择是2":
System.out.println("金钱");
break;
case "我的选择是3":
System.out.println("权力");
break;
default:
System.out.println("对不起你的选择不是以下选择");
break;
}
System.out.println("为什么说说你的理由");
String liyu =s.next();
System.out.println(liyu);
}
}
我的选择是:
注意:1.switch也是多分支,不能用在表达式范围的条件分支上。2.switch中的常量值的取值类型有限定:byte,short,int,char,string,枚举。3.在条件是明确有限的情况下使用比较合适。
执行规则:按照switch中的值去依次匹配caes分支的值,遇到break;则结束循环。
最后祝大家以梦为马,不负韶华。