您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页JavaSE语法系列——第四节-逻辑控制

JavaSE语法系列——第四节-逻辑控制

来源:化拓教育网

1. 顺序结构

顺序结构比较简单,按照代码书写的顺序一行一行执行

System.out.println("aaa"); 
System.out.println("bbb"); 
System.out.println("ccc"); 
// 运行结果 
aaa
bbb
ccc

如果调整代码的书写顺序, 则执行顺序也发生变化

System.out.println("aaa"); 
System.out.println("ccc"); 
System.out.println("bbb"); 
// 运行结果 
aaa
ccc
bbb

2. 分支结构

2.1 if 语句
if(布尔表达式){//必须是 true或者false 是 0 1不可以
 // 语句 
 }

如果布尔表达式结果为true,执行if中的语句,否则不执行。
比如:小明,如果这次考试考到90分或以上,给你奖励一个鸡腿。

int score = 92; 
if(score >= 90){ 
System.out.println("吃个大鸡腿!!!"); 
}

如果布尔表达式结果为true,则执行if中语句,否则执行else中语句。
比如:小明,如果这次考到90分以上,给你奖励一个大鸡腿,否则奖你一个大嘴巴子

int score = 92; 
if(score >= 90){ 
System.out.println("吃个大鸡腿!!!"); }
else{ 
System.out.println("挨大嘴巴子!!!"); }
  1. 语法格式3
if(score >= 90){ 
System.out.println("优秀"); }
else if(score >= 80 && score < 90){ 
System.out.println("良好"); }
else if(score >= 70 && score < 80){ 
System.out.println("中等"); }
else if(score >= 60 && score < 70){ 
System.out.println("及格"); }
else if(score >= 0 && score < 60){ 
System.out.println("不及格"); }
else{ 
System.out.println("错误数据"); }

【练习】

1. 判断一个数字是奇数还是偶数

2. 判断一个数字是正数,负数,还是零

3. 判断一个年份是否为闰年
int year = 2000; 
if (year % 100 == 0) 
{ // 判定世纪闰年 
if (year % 400 == 0) { 
System.out.println("是闰年"); } 
else { 
System.out.println("不是闰年"); } } 
else { // 普通闰年 
if (year % 4 == 0) { 
System.out.println("是闰年"); } 
else { 
System.out.println("不是闰年"); } }

【注意事项】

虽然两种方式都是合法的, 但是 Java 中更推荐使用风格1, { 放在 if / else 同一行. 代码跟紧凑

分号问题

悬垂 else 问题

int x = 10; 
int y = 10; 
if (x == 10) 
if (y == 10) 
System.out.println("aaa"); 
else
System.out.println("bbb");

if / else 语句中可以不加 大括号 . 但是也可以写语句(只能写一条语句). 此时 else 是和最接近的 if 匹配.
但是实际开发中我们 不建议 这么写. 最好加上大括号.

2.2 switch 语句

基本语法

switch(表达式){
case 常量值1:{
语句1; 
[break;]
}
case 常量值2:{
语句2; [break;]
}
switch (表达式) {
case 常量值1: {
	语句1; [break; ]
}
case 常量值2: {
	语句2; [break; ]
}
		 ...
default: {
			 内容都不满足时执行语句; [break; ]
		 }
}

执行流程:

  1. 先计算表达式的值
  2. 和case依次比较,一旦有响应的匹配就执行该项下的语句,直到遇到break时结束
  3. 当表达式的值没有与所列项匹配时,执行default

代码示例: 根据 day 的值输出星期

int day = 1; switch (day) {
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;
}

【注意事项】
多个case后的常量值不可以重复
switch的括号内只能是以下类型的表达式:

基本类型:byte、char、short、int,注意不能是long类型
引用类型:String常量串、枚举类型

double num = 1.0;
switch (num) {
case 1.0: System.out.println("hehe");
	break;
case 2.0: System.out.println("haha");
	break;
}// 编译出错 
Test.java:4: 错误: 不兼容的类型:double转换到int可能会有损失 
switch(num) { 
	^ 1 个错误

break 不要遗漏, 否则会失去 “多分支选择” 的效果

int day = 1; 
switch (day) {
case 1: System.out.println("星期一"); // break;
case 2: System.out.println("星期二");
	break;
}// 运行结果 星期一 星期二

switch 不能表达复杂的条件

// 例如: 如果 num 的值在 10 到 20 之间, 就打印 hehe 
// 这样的代码使用 if 很容易表达, 但是使用 switch 就无法表示. 
if (num > 10 && num < 20) {
 System.out.println("hehe"); 
 }

switch 虽然支持嵌套, 但是很丑,一般不推荐

综上, 我们发现, switch 的使用局限性是比较大的

3. 循环结构

3.1 while 循环

基本语法格式:

while(循环条件){ 
循环语句; 
}

循环条件为 true (不再是0,1), 则执行循环语句; 否则结束循环

代码示例1: 打印 1 - 10 的数字

代码示例2: 计算 1 - 100 的和

代码示例3: 计算 5 的阶乘

代码示例4: 计算 1! + 2! + 3! + 4! + 5!

这里我们发现, 当一个代码中带有多重循环的时候, 代码的复杂程度就大大提高了. 而比较复杂的代码就更容易出错.
后面我们会采用更简单的办法来解决这个问题.

注意事项

  1. 和 if 类似, while 下面的语句可以不写 { } , 但是不写的时候只能支持一条语句. 建议还是加上 { }
  2. 和 if 类似, while 后面的 { 建议和 while 写在同一行.
  3. 和 if 类似, while 后面不要多写 分号, 否则可能导致循环不能正确执行

此时 ; 为 while 的语句体(这是一个空语句), 实际的 { } 部分和循环无关. 此时循环条件 num <= 10 恒成立, 导致代码死循环了.

3.2 break

break 的功能是让循环提前结束.

代码示例: 找到 100 - 200 中第一个 3 的倍数
	  int num = 100; 
	  while (num <= 200) {
		  if (num % 3 == 0) {
			  System.out.println("找到了 3 的倍数, 为:" + num);
			  break;
		  }num++;
	  }// 执行结果 找到了 3 的倍数, 为:102

执行到 break 就会让循环结束.

3.3 continue

continue 的功能是跳过这次循环, 立即进入下次循环

代码示例: 找到 100 - 200 中所有 3 的倍数

执行到 continue 语句的时候, 就会立刻进入下次循环(判定循环条件), 从而不会执行到下方的打印语句

3.4 for 循环

【基本语法】

表达式1: 用于初始化循环变量初始值设置,在循环最开始时执行,且只执行一次
表达式2: 循环条件,满则循环继续,否则循环结束
表达式3: 循环变量更新方式

【代码示例】

1. 打印 1 - 10 的数字

2. 计算 1 - 100 的和

3. 计算 5 的阶乘

4. 计算 1! + 2! + 3! + 4! + 5!


【注意事项】 (和while循环类似)

  1. 和 if 类似, for 下面的语句可以不写 { } , 但是不写的时候只能支持一条语句. 建议还是加上 { }
  2. 和 if 类似, for 后面的 { 建议和 while 写在同一行.
  3. 和 if 类似, for 后面不要多写 分号, 否则可能导致循环不能正确执行.
  4. 和while循环一样,结束单趟循环用continue,结束整个循环用break
3.5 do while 循环(选学)

【基本语法】

先执行循环语句, 再判定循环条件,循环条件成立则继续执行,否则循环结束。
例如:打印 1 - 10

【注意事项】

  1. do while 循环最后的分号不要忘记
  2. 一般 do while 很少用到, 更推荐使用 for 和 while.

4. 输入输出

4.1 输出到控制台

println 输出的内容自带 \n, print 不带 \n
printf 的格式化输出方式和 C 语言的 printf 是基本一致的

格式化字符串

4.2 从键盘输入

使用 Scanner 读取字符串/整数/浮点数


使用 Scanner 循环读取 N 个数字,并求取其平均值

Scanner sc = new Scanner(System.in); 
int sum = 0; 
int num = 0; 
while (sc.hasNextInt()) { 
int tmp = sc.nextInt(); 
sum += tmp; num++; 
}
System.out.println("sum = " + sum); 
System.out.println("avg = " + sum / num); 
sc.close(); 
// 执行结果 1040.0
50.5
^Z
sum = 150.5
avg = 30.1

5. 猜数字游戏


参考代码

random


######## 范围 [0,n) 需要加减 适应范围

6. 练习


    public static void main1(String[] args) {
        Scanner scan = new Scanner(System.in);
        int age = scan.nextInt();
        if(age < 18) {
            System.out.println("少年!");
        }else if(age >= 18 && age < 28) {
            System.out.println("青年!");
        }else if(age >= 29 && age < 55) {
            System.out.println("中年!");
        }else {
            System.out.println("老年!");
        }
    }
}

    public static boolean isPrime(int n) {
        int i = 2;
        for (; i <= Math.sqrt(n); i++) {
            if(n % i == 0) {
                //System.out.println(n+": 不是素数!");
                break;
            }
        }
        if(i > Math.sqrt(n)) {
            //System.out.println(n+": 是素数!");
            return true;
        }
        return false;
    }

    public static void main5(String[] args) {
        for (int i = 1; i < 101; i++) {
            boolean ret = isPrime(i);
            if(ret) {
                System.out.println(i+" 是素数!");
            }
        }
    }

    public static void main6(String[] args) {

        for (int j = 1; j < 101; j++) {
            //int n = 19;
            int i = 2;
            for (; i <= Math.sqrt(j); i++) {
                if(j % i == 0) {
                    //System.out.println("不是素数!");
                    break;
                }
            }
            if(i > Math.sqrt(j)) {
                System.out.println(j+" 是素数!");
            }
        }

    }

    public static void main3(String[] args) {
        int n = 9;
        int i = 2;
        for (; i <= n/2; i++) {
            if(n % i == 0) {
                System.out.println("不是素数!");
                break;
            }
        }
        if(i > n/2) {
            System.out.println("是素数!");
        }
    }

    public static void main2(String[] args) {
        int n = 7;
        int i = 2;
        for (; i < n; i++) {
            if(n % i == 0) {
                System.out.println("不是素数!");
                break;
            }
        }
        //1、i==n  2、n%i==0
        if(i == n) {
            System.out.println("是素数!");
        }
    }

    public static void main7(String[] args) {
        for (int i = 1; i <= 9 ; i++) {
            for (int j = 1; j <= i ; j++) {
                System.out.print(i+"*"+j+"="+i*j+" ");
            }
            System.out.println();
        }
    }

    //TODO:求最小公倍数
    public static void main9(String[] args) {
        //辗转相除法
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = a%b;
        while (c != 0) {
            a = b;
            b = c;
            c = a%b;
        }
        System.out.println(b+" 是最大公约数!");
    }

Math.pow()
    public static void main10(String[] args) {

        for (int i = 1; i < 999999; i++) {
            int count = 0;//位数
            int tmp = i;
            while (tmp != 0) {
                count++;//3
                tmp = tmp / 10;//0
            }
            //tmp == 0;  count = 3; i = 123
            tmp = i;//123
            int sum = 0;
            while (tmp != 0) {
                sum += Math.pow(tmp % 10,count);
                //sum = (int)(sum + Math.pow(tmp % 10,count));
                tmp /= 10;
            }
            //此时的sum 藜麦存储的 是tmp的每一位的count次方和
            if(sum == i) {
                System.out.println(i);
            }
        }
    }
二进制中 1的个数
1. 右移31次
2. 无符号右移>>>,while(n !=0)
3. x & (x - 1)

    public static void main14(String[] args) {
        int n = -1;
        int count = 0;
        while (n != 0) {
            n = n &(n-1);
            count++;
        }
        System.out.println(count);
    }

    public static void main13(String[] args) {
        int n = -1;
        int count = 0;
        while (n != 0) {
            if((n & 1) != 0) {
                count++;
            }
            n = n >>> 1;//  >>>
        }
        System.out.println(count);
    }

    public static void main12(String[] args) {
        int n = 7;
        int count = 0;
        for (int i = 0; i < 32; i++) {
            if(  ((n >> i) & 1) != 0   ) {
                count++;
            }
        }
        System.out.println(count);
    }

    public static void main15(String[] args) {
        int n = 7;
        for (int i = 31; i >= 1 ; i-=2) {
            //偶数位
            System.out.print(((n >> i) & 1)+" ");
        }

        System.out.println();
        for (int i = 30; i >= 0 ; i-=2) {
            //奇数位
            System.out.print(((n >> i) & 1)+" ");
        }

    }

    public static void main16(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int count = 3;
        while (count != 0) {
            System.out.println("请输入你的密码:");
            String password = scanner.nextLine();
            if(password.equals("123456")) {
                System.out.println("登录成功!");
                break;
            }else {
                count--;
                System.out.println("你还有 "+count+"次机会!");
            }
        }
    }

训练

1. 输出乘法口诀表

2. 模拟登录

3. 水花仙数

4. 打印x形

5. 求最大公约数

6. 输出润年

7. 打印素数

8. 判断素数

9. 9出现的次数

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务