一、流程控制语句
1、顺序结构
2、选择结构
- 格式一:if ;
- 格式二: if else;
- 格式三:if elseif else;
- 格式四:switch语句;
public class Demo2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数字(1-7):");
int weekDay = sc.nextInt();
/** 1. swtich表达式可以为: byte,short,int,char
* JDK5以后可以为枚举, jdk7以后可以为字符串
* 2. 在执行过程中,表达式和case的值进行匹配,相同则执行对应语句,
* 遇见break则终止switch
* */
switch(weekDay){
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期天");
break;
default:
System.out.println("输入格式有误");
break;
}
}
}
switch的case穿透
public class CaseSpire {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数字 1-12");
int season = sc.nextInt();
// case穿透: 如果一个case匹配上,没有break,则会继续往下走,执行下面的循环体语句
switch (season){
case 1:
case 2:
case 3:
System.out.println("春天");
break;
case 4:
case 5:
case 6:
System.out.println("夏天");
break;
case 7:
case 8:
case 9:
System.out.println("秋天");
break;
case 10:
case 11:
case 12:
System.out.println("冬天");
break;
}
}
}
3、循环结构
- for循环;
- while循环;
- do while循环:至少执行一次循环体语句‘’
- for循环后,初始化变量不能使用,但while循环初始化变量可以继续使用;
- 推荐顺序: for–while—dowhile
public class WaterFlower {
public static void main(String[] args) {
// 打印100-1000的所有水仙花数
for (int i = 100; i<1001; i ++){
int ge = i %10;
int shi = i/10%10;
int bai = i/100;
if(ge*ge*ge+shi*shi*shi+bai*bai*bai == i){
System.out.println(i);
}
}
}
}
public class While {
public static void main(String[] args) {
int i = 0;
while(i<10){
System.out.println(i);
i++;
}
}
}
public class DoWhile {
public static void main(String[] args) {
int i = 0;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
4、break及continue关键字
- break关键字: 用于跳出当前循环;
public class DoWhile {
public static void main(String[] args) {
// 输出语句只能执行3次,用于跳出大的循环
for (int i = 0; i<10; i++){
if (i==3){
break;
}
System.out.println("hello word!");
}
}
}
- continue关键字:跳出本次循环,继续执行下一次循环;
public class DoWhile {
public static void main(String[] args) {
// 只有i=3时没有执行下面的输出语句
for (int i = 0; i<10; i++){
if (i==3){
continue;
}
System.out.println(i);
}
}
}
二、练习
1. 猜数字小游戏
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 产生[0,99]的数字
Random random = new Random();
int num =random.nextInt(100);
while (true){
System.out.println("请输入一个数字");
int c = sc.nextInt();
if(num>c){
System.out.println("小了");
}else if(num<c){
System.out.println("大了");
}else{
System.out.println("猜中了");
// 跳出while循环
break;
}
}
}
}
2. 不死神兔
public class RabbitNum {
public static void main(String[] args) {
int[] arr = new int[20];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i<arr.length; i++){
arr[i] = arr[i-1] + arr[i-2];
}
System.out.println("第十二个月兔子对数" + arr[19]);
}
}