Java流程控制

示例代码如下:

1.分支结构
int score = 90;
if(score >= 90){
	System.out.println("good");
}

if(score >= 90){
	System.out.println("good");
}else{
	System.out.println("not good");
}

if(score >= 90){
	System.out.println("so good");
}else if (score >= 80){
	System.out.println("good");
}else{
	System.out.println("just so so");
}

int i = 1;

// switch (表达式) {}
// 表达式可以是byte short int char String 枚举
switch (i) {
	case 1:
		System.out.println("1");
		break;
	case 2:
		System.out.println("2");
		break;
	default:
		System.out.println("other");
		break;
}

2.循环结构
for(int i=0; i<10; i++){
	System.out.println(i);
}


int res = 0;
for(int i=1; i<=10; i++){
	res += i;
}
System.out.println(res);

// 水仙花数
for(int i=100; i<1000; i++){
	int b = i / 100;
	int s = i / 10 % 10;
	int g = i % 10;
	if(b*b*b + s*s*s + g*g*g == i){
		System.out.println(i);
	}
}
// while
double height = 0.01;
int count = 0;
while (height < 8848){
	height *= 2;
	count++;
}
System.out.println(count);

// do... while
int i = 0;
do {
	System.out.println(i);
	i++;
}while(i < 10);

char c = '*';
// 控制行数
for(int i=1; i<=5; i++){
	// 控制每行输出的字符数
	for(int j=1; j<=i; j++){
		System.out.print(c);
	}
	System.out.println();
}

// 九九乘法表
for(int i=1; i<=9; i++){
	for(int j=1; j<=i; j++){
		System.out.print(j + "*" + i + "=" + j * i + " ");
	}
	System.out.println();
}

// 数组的定义
int[] arr = {1, 2, 3, 4, 5};
// 数组遍历
for(int ele : arr){
	System.out.println(ele);
}

// break continue return

for(int i=0; i<=10; i++){
	if(i == 5){
		break;
	}
	System.out.println(i);
}

for(int i=0; i<=10; i++){
	if(i == 5){
		continue;
	}
	System.out.println(i);
}

// 跳出多重循环
outer:
for(int i=0; i<=10; i++){
	if(i == 5){
		break outer;
	}
	System.out.println(i);
}

// return中止循环
for(int i=0; i<5; i++){
	for(int j=0; j<5; j++){
		if(j == 2){
			return;
		}
		System.out.println(i+ " " +j);
	}
}

posted @ 2021-04-04 22:06  程序员陈师兄cxycsx  阅读(39)  评论(0)    收藏  举报