循环四要素:
初始化循环变量
循环条件
循环体
更新循环变量
一、for循环
int sum3 = 0;
for(int j = 1;j < 101;j++){
sum3 += j;
}
System.out.println("1+2+3+4+....+100的和是:"+sum3 );
for(int jj = 1 ; jj <= 9 ;jj++){
for(int jjj = 1; jjj <= jj ; jjj++){
System.out.print(jj + "*" + jjj + "=" + jj * jjj + " ");
}
System.out.println();
}
二、while循环
- 基础语法
初始化循环变量
while(循环条件){
// 循环体
// 更新循环变量
}
int num = 0;
while(num < 10){
System.out.println("hello world");
num++;
}
Scanner scanner = new Scanner(System.in);
String flag = "Y";
while(flag.equals("Y")){
// 接收用户输入的变量
System.out.print("请输入学生学号:");
int id = scanner.nextInt();
// String id = scanner.next()
switch(id){
case 1:
System.out.println("张三的成绩是98");
break;
case 2:
System.out.println("李四的成绩是96");
break;
case 3:
System.out.println("王五的成绩是94");
break;
default:
System.out.println("请输入正确的学号");
break;
}
System.out.print("是否继续?Y/N");
flag = scanner.next();
}
三、do while 循环
int iii = 1,sum2 = 0;
do{
sum2 += iii;
iii++;
}while(iii <= 100);
System.out.println("1+2+3+4+....+100的和是:"+sum2 );
四、for each 循环
// break 结束整个循环
int r = 1,sum4 = 0;
while(true){
sum4 += r;
if(sum4 > 100){
break;
}
r++;
}
System.out.println("1+2+3+4+....+100加到第"+r+"个数和超过了100");
label: for(int y = 1; y < 4; y++){
for (int x = 1; x < 10; x++){
if(x % 4 == 0){
break label;
}
System.out.println("break label:" + x);
}
}
// continue 只结束当前循环
label: for(int yy = 1; yy < 4; yy++){
for (int xx = 1; xx < 10; xx++){
if(xx % 4 == 0){
continue label;
}
System.out.println("continue label:" + xx);
}
}