package main;
import java.util.Scanner;
public class Study {
public static void main(String[] args) {
//while 循环
int sum = 0;
int i = 0;
while (i <= 100) {
sum += i;
i++;
}
System.out.println("sum=" + sum);
System.out.println("-------------------------");
// switch语句
int reason = 2;
switch (reason) {
case 1:
System.out.println("num is 1");
break;
case 2:
System.out.println("num is 2");
break;
case 3:
System.out.println("num is 3");
break;
default:
System.out.println("num is null");
}
/*
练习1:给定一个月份,打印是哪个季节
3-5:春季
6-8:夏季
9-11:秋季
12-2:冬季
*/
System.out.println("-------------------------");
int month = 1;
if (month >= 1 && month <= 12) {
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;
default:
System.out.println("冬季");
}
} else {
System.out.println("月份不符合要求");
}
System.out.println("-------------------------");
// do while(首先执行循环体,在执行循环条件)
int a = 1;
do {
System.out.println("a=" + a);
a++;
} while (a <= 5);
System.out.println("-------------------------");
//练习,1-5阶乘的和
int j = 1;
int ret = 1;
int sum2 = 0;
do {
ret *= j;
j++;
sum2 += ret;
} while (j <= 5);
// System.out.println("ret="+ret);
System.out.println("sum2=" + sum2);
System.out.println("-------------------------");
// break和continue
for (int h = 1; h <= 10; h++) {
if (h == 3) {
//break;//跳出当前的循环结构
continue;//只是终止了某一次循环,下一次循环继续
}
System.out.println("h:" + h);
}
System.out.println("-------------------------dd");
//双重循环
for (int f = 0; f < 10; f++) {
System.out.println("-------------------->f:" + f);
for (int k = 0; k < 10; k++) {
if (k == 2) {
//break;
break;//跳出当前的循环结构,没有对外层的循环结构产生影响
//continue;//只是结束了内层循环的某一次循环
// return;//结束了整个方法的执行,和break out效果一样
}
System.out.println("k:" + k);
}
}
}
}
Java基础语法(switch语句、do...while循环、break和continue关键字)
于 2024-06-08 10:15:53 首次发布