本文中将对Java中的三种逻辑控制结构进行介绍,包括顺序结构、分支结构以及循环结构。
一、顺序结构
顾名思义,代码是按照从上到下的顺序一一执行的。
System.out.println("first");
System.out.println("second");
//运行结果
first
second
如果调整其顺序
System.out.println("second");
System.out.println("first");
//运行结果
second
first
二、分支结构
分支结构包括:if-else
和switch-case
。
1、if、if-else
① 单独使用if
int x = 10;
if( x < 20 ){
System.out.println("x < 20成立");
② 使用if-else
int x = 10;
if( x < 20 ){
System.out.println("x < 20成立");
else
System.out.println("x < 20不成立");
③ 使用if-else if-else
int x = 10;
if( x < 20 ){
System.out.println("x<20成立");
else if( x > 20)
System.out.println("x>20成立");
else{
System.out.println("x<20以及x>20均不成立");
}
④ 嵌套使用if-else
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.println("X = 30 and Y = 10");
}
}
2、switch-case
语法格式:
switch(expression){
case value :
//语句
break; //可选
case value :
//语句
break; //可选
//你可以有任意数量的case语句
default : //可选,如果上面所有的case都不符合则进入default
//语句
}
示例:
public class Test {
public static void main(String args[]){
char grade = 'D';
switch(grade)
{
case 'A' :
System.out.println("优秀");
break;
case 'B' :
case 'C' :
System.out.println("良好");
break;
case 'D' :
System.out.println("及格");
break;
case 'F' :
System.out.println("还需努力");
break;
default :
System.out.println("未知");
}
System.out.println("你的评价是 " + grade);
}
}
注: switch
括号内的条件只能是byte、char、short、int、String、枚举类型。switch
支持嵌套但一般不使用,因为写出的代码不够美观。
三、循环结构
1、while
语法格式:
while(循环条件){
//代码语句
}
循环条件为true则循环,为false则退出。while循环支持嵌套。
示例:
//打印1到10
int x = 1;
while( x <= 10 ) {
System.out.print(x+" ");
x++;
}
2、do-while
先执行循环语句,再判定循环条件,成立则继续运行,否则跳出循环。
语法格式:
do {
//代码语句
}while(布尔表达式);
示例:
int x = 10;
int num = 1;
do {
System.out.println(num);
num++;
} while (num <= 10)
3、for
语法格式:
for(初始化; 布尔表达式; 更新) {
//代码语句
}
示例:
int[] arr = {10, 20, 30, 40, 50};
for(int i =0;i < arr.length;i++){
System.out.print( arr[i] );
System.out.print(",");
}
System.out.print("\n");
4、break和continue关键字
break
关键字主要循环语句或者switch
语句中,用来跳出当前循环。continue
关键字是让程序立刻跳转到下一次循环的迭代。
示例:
//break关键字
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
// x 等于 30 时跳出循环
if( x == 30 ) {
break;
}
System.out.print( x + " ");
}
//运行结果:10 20
//continue关键字
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x + " ");
}
//运行结果:10 20 40 50