关于java:java基础语法分支结构

8次阅读

共计 1051 个字符,预计需要花费 3 分钟才能阅读完成。

java 分支构造有两种:
1,if 语句,
2,switch 语句


if 语句

格局一:

 if(条件表达式){​    执行代码块;}

【当条件表达式的后果为 true 时,执行代码块】

例:

if(11>5){System.out.println("11>5");
}

格局二:

 if(条件表达式){​    执行代码块 1;}else {执行代码块 2;}

【当条件表达式的后果为 true 时,执行代码块 1,否则执行代码块 2】

例:

int year = 100;
if(0==year%400 || (0==year%4&& 0!=year%100)){System.out.println("是润年");
}else{System.out.println("是平年");
}

格局三:

 if(条件表达式 1){执行代码块 1;}else if (条件表达式 2){​    执行代码块 2;}else{执行代码块 3;}

【当条件表达式的后果为 true 时,执行代码块 1,否则判断条件表达式 2,当条件表达式 2 的后果为 true,执行代码块 2,如果两个条件都不满足,执行代码块 3】

例:

char ch = '1';
if('A'<=ch && 'Z' >=ch){System.out.println("字符是:大写字母");
}else if('a'<=ch && 'z' >= ch){System.out.println("字符是:小写字母");
}else if('0' <= ch && '9' >= ch){System.out.println("字符是:数字字符");
}else{System.out.println("字符是:其余字符");
}

switch 语句

格局:

switch(表达式 1){
​      case 常量 1: 
​           执行代码块 1;
​           break;// 完结语句    
​     default:
​            执行默认代码块; 
​           break;}

【判断表达式的后果是否与表达式 1 统一,如果统一,执行代码块 1,如果不统一,执行默认代码块】

例:

int month = 101;
switch (month) {
case 3:
case 4:
case 5:
     System.out.println("春天");
break;

case 6:
case 7:
case 8:
    System.out.println("夏天");
break;

case 9:
case 10:
case 11:
     System.out.println("秋天");
break;

case 12:
case 1:
case 2:
     System.out.println("冬天");
 break;
default:
    System.out.println("输出谬误,请从新输出~~");}
正文完
 0