0
点赞
收藏
分享

微信扫一扫

初识Java(四)---- Java中的逻辑控制结构

zhongjh 2022-02-27 阅读 211

目录

一、顺序结构

二、分支结构

🍓if 语句

🍓switch 语句

三、循环结构

🍓while 循环

🍓break

🍓continue

🍓for循环

🍓do...while()循环

四、Java中的输入输出

🍓输出到控制台

🍓格式化字符

🍓从键盘输入

 五、总结


一、顺序结构

顺序结构比较简单, 代码按照书写的顺序一行一行执行。程序的执行顺序与代码的书写顺序有关。

public class TestDemo2 {
    public static void main(String[] args) {
        System.out.println("hello");
        System.out.println("world");
        System.out.println("Java");
    }
}

二、分支结构

🍓if 语句

🌀单分支

if(布尔表达式){
    //条件满足时执行代码
}

🌀双分支

if(布尔表达式){
    //条件满足时执行代码
}else{
    //条件不满足时执行代码
}

🌀多分支

if(布尔表达式){
    //条件满足时执行代码
}else if(布尔表达式){
    //条件满足时执行代码
}else{
    //条件都不满足时执行代码
}

🎄练习1:判断一个数字是奇数还是偶数

public class TestDemo2 {
    public static void main(String[] args) {
        int num = 10;
        if (0 == num % 2) {
            System.out.println("偶数");
        } else {
            System.out.println("奇数");
        }
    }
}

🎄 练习2:判断一个数字是正数还是负数

public class TestDemo2 {
    public static void main(String[] args) {
        int num = -10;
        if (num > 0) {
            System.out.println("num 是正数");
        } else if (num < 0) {
            System.out.println("num 是负数");
        } else {
            System.out.println("num 是0");
        }
    }
}

🎄练习3:判断某一年份是否是闰年

  • 普通闰年:公历年份是4的倍数,且不是100的倍数的,为闰年(如2004年、2020年等就是闰年)。
  • 世纪闰年:公历年份是整百数的,必须是400的倍数才是闰年(如1900年不是闰年,2000年是闰年)。

💦代码1:

public class TestDemo2 {
    public static void main(String[] args) {
        int year = 2022;
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            System.out.println(year + "是闰年");
        } else {
            System.out.println(year + "不是闰年");
        }
    }
}

💦代码2:

public class TestDemo2 {
    public static void main(String[] args) {
        int year = 2000;
        if (year % 100 == 0) {
            //判断世纪闰年
            if (year % 400 == 0) {
                System.out.println(year + "是世纪闰年");
            } else {
                System.out.println(year + "不是闰年");
            }
        } else {
            if (year % 4 == 0) {
                //判断普通闰年
                System.out.println(year + "是普通闰年");
            } else {
                System.out.println(year + "不是闰年");
            }
        }
    }

}

运行结果

💥注意事项1:悬垂 else 问题

public class TestDemo2 {
    public static void main(String[] args) {
               int x = 10;
        int y = 10;
        if (x == 10)
            if (y == 20)
                System.out.println("aaa");
       else
                System.out.println("bbb");
    }

}

运行结果

🌊 if ... else 语句中可以不使用大括号,但是只能写一条语句。此时 else 是和最接近的 if 匹配。

✨ 建议:在写代码的时候不要省略括号。

💥注意事项2:代码风格

int x = 10;
if (x == 10) {
    // 满足条件
} else {
    // 不满足条件
}

👀Java中的代码风格与C语言不同。

💥注意事项3:分号问题

public class TestDemo2 {
    public static void main(String[] args) {
        int x = 20;
        if (x == 10) ; {
            System.out.println("hehe");
        }
    }
}

运行结果

if 后面多写了一个分号, 导致分号成为了 if 语句的语句体, 而 { } 中的代码已经成为了和一个 if 无关的代码块

🍓switch 语句

基本语法

    switch(整数|枚举|字符|字符串){
        case 内容1 : {
            内容满足时执行语句;
        [break;]
        }
        case 内容2 : {
            内容满足时执行语句;
        [break;]
        }
        ...
        default:{
            内容都不满足时执行语句;
        [break;]
        }
    }

🎄练习:根据 day 的值输出星期

public class TestDemo2 {
    public static void main(String[] args) {
        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;
        }
    }
}
  • 根据 switch 中值的不同, 会执行对应的 case 语句. 遇到 break 就会结束该 case 语句.
  • 如果 switch 中的值没有匹配的 case, 就会执行 default 中的语句.
  • 建议一个 switch 语句最好都要带上 default。

💥注意事项1:break 不要遗漏, 否则会失去 "多分支选择" 的效果。

public class TestDemo2 {
    public static void main(String[] args) {
        int day = 1;
        switch (day) {
            case 1:
                System.out.println("星期一");
            case 2:
                System.out.println("星期二");
                break;
        }
    }

}

运行结果

🍉如果不写 break ,那么 case 语句会依次向下执行, 从而失去了多分支的效果。

💥注意事项2:

  • switch 中的值只能是 整数 | 枚举 | 字符 | 字符串。
  • JDK1.5开始引入枚举:枚举也可以做switch的参数。
public class TestDemo2 {
    public static void main(String[] args) {
        double num = 1.0;
        switch (num) {
            case 1.0:
                System.out.println("hehe");
                break;
            case 2.0:
                System.out.println("haha");
                break;
        }
    }
}

使用字符串做 switch 的参数

public class TestDemo2 {
    public static void main(String[] args) {
        String str = "hello";
        switch (str) {
            case "abc":
                System.out.println(1);
                break;
            case "hello":
                System.out.println(2);
                break;
            default:
                System.out.println("错误");
        }
    }
}

运行结果

💥注意事项3:switch 不能表达复杂的条件

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

💥注意事项4:switch 虽然支持嵌套, 但是很丑~

public class TestDemo2 {
    public static void main(String[] args) {
        int x = 1;
        int y = 1;
        switch (x) {
            case 1:
                switch (y) {
                    case 1:
                        System.out.println("hehe");
                        break;
                }
                break;
            case 2:
                System.out.println("haha");
                break;
        }
    }
}

💦结合以上的特得出,:switch 的使用局限性是比较大的。

Java当中,不能做 switch 参数的数据类型有哪些?

  • long、float、double、boolean

三、循环结构

🍓while 循环

基本语法格式:

while(循环条件(布尔表达式)){
    循环语句;
}

循环条件为 true 时, 执行循环语句; 否则结束循环  。

🎄练习1:打印 1 - 10 的数字

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 10) {
            System.out.println(i);
            i++;
        }
    }
}

🎄练习2:计算1到100的和

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 1;
        int sum = 0;
        while (i <= 100) {
            sum += i;
            i++;
        }
        System.out.println(sum);
    }
}

🎄练习3:计算5的阶乘

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 1;
        int temp = 1;
        while (i <= 5) {
            temp *= i;
            i++;
        }
        System.out.println(temp);
    }
}

🎄练习4:计算1到5的阶乘之和

public class TestDemo2 {
    public static void main(String[] args) {
        int num = 1;
        int sum = 0;
        // 外层循环负责求阶乘的和
        while (num <= 5) {
            int ret = 1;
            int tmp = 1;
            // 里层循环负责完成求每一数的阶乘.
            while (tmp <= num) {
                ret *= tmp;
                tmp++;
            }
            sum += ret;
            num++;
        }
        System.out.println("sum = " + sum);
    }
}

💥注意事项

  • 和 if 类似, while 下面的语句可以不写 { } , 但是不写的时候只能支持一条语句. 建议还是加上 { }
  • 和 if 类似, while 后面的 { 建议和 while 写在同一行.
  • 和 if 类似, while 后面不要写分号, 否则可能导致循环不能正确执行
public class TestDemo2 {
    public static void main(String[] args) {
        int num = 1;
        while (num <= 10) ;
        {
            System.out.println(num);
            num++;
        }
    }
}

🍓break

break 的功能是让循环提前结束。
🎄练习:输出100到200中第一个 3 的倍数。

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 100;
        while (i <= 200) {
            if (i % 3 == 0) {
                System.out.println("找到了第一个3的倍数" + i);
                break;
            }
            i++;
        }
    }
}

循环中执行到 break 就结束循环。

🍓continue

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

🎄练习:输出 100 - 200 中所有 3 的倍数。

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 100;
        while (i <= 200) {
            if (i % 3 != 0) {
                i++;
                continue;
            }
            System.out.println("3的倍数" + i);
            i++;
        }
    }
}

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

💥注意事项:

  • break 和 continue 都必须在循环中使用。特殊:break可以在switch中使用。
  • 如果是多重循环,break只能跳出离它最近的那个循环。

🍓for循环

基本语法

for(表达式1;表达式2(布尔表达式);表达式3){
    循环体;
}

🚀说明:

  • 表达式1: 用于初始化循环变量.
  • 表达式2: 循环条件
  • 表达式3: 更新循环变量.

🌊相比于 while 循环, for 循环将这三个部分合并在一起, 写代码时不容易遗漏

🎄练习:计算 1! + 2! + 3! + 4! + 5!

public class TestDemo2 {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            int temp = 1;
            for (int j = 1; j <= i; j++) {
                temp *= j;
            }
            sum += temp;
        }
        System.out.println(sum);
    }
}

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

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

🍓do...while()循环

基本语法

do{
    循环语句;
}while(循环条件(布尔表达式));

🎄 练习:打印 1~10

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println(i);
            i++;
        } while (i <= 10);
    }
}

💥注意事项:

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

四、Java中的输入输出

输出语句在前面的代码中已经见到了,这里再简单的总结一下。

🍓输出到控制台

基本语法

System.out.println("输出且换行"); // 输出一个字符串, 带换行
System.out.print("输出不换行"); // 输出一个字符串, 不带换行
System.out.printf("%d\n",10); // 格式化输出

🚀说明:

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

🌌示例:

public class TestDemo {
    public static void main(String[] args) {
        System.out.println("Hello World");
        int x = 10;
        System.out.printf("x=%d\n",x);
    }
}

运行结果

🍓格式化字符

🍓从键盘输入

读入一个字符(了解)

  • 直接使用 System.in.read 可以读入一个字符. 但是需要搭配异常处理(异常的内容后面的文章中会讲到)

🌌示例:

import java.io.IOException; // 需要导入 IOException 包

public class TestDemo {
    public static void main(String[] args) throws IOException {
        System.out.print("Enter a Char:");
        char i = (char) System.in.read();
        System.out.println("your char is :" + i);
    }

}

 运行结果

这种方式比较麻烦, 只是了解一下就可以了。

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

  • 使用 Scanner 需要导包:import java.util.Scanner;
  • Scanner sc = new Scanner(System.in); System.in:从键盘读入数据

🌌示例:

import java.util.Scanner;// 需要导入 util 包

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("输入姓名:");
        String name = sc.next();
        System.out.print("输入年龄:");
        int age = sc.nextInt();
        System.out.print("输入成绩:");
        float score = sc.nextFloat();
        System.out.println("姓名:" + name + "\n年龄:" + age + "\n成绩:" + score);
        sc.close(); // 注意, 要记得调用关闭方法
    }

}

运行结果

next()在读取字符串时遇到空格就结束,nextLine()会读取空格字符

🌌示例:next();

import java.util.Scanner;// 需要导入 util 包

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();
        System.out.println(str1);
    }
}

运行结果

🌌示例:nextLine();

import java.util.Scanner;// 需要导入 util 包

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.nextLine();
        System.out.println(str1);
    }

}

运行结果

💥注意事项:

  • 输入整数:nextInt();输出字符串:next(); 或 nextLine();
  • nextInt();不可以放在next();或 nextLine(); 前面使用。
  • sc.close(); 在Java中认为Scanner相当于一个文件,在使用时就会打开它,使用结束就要将其关闭。一般情况下不加 close();也不影响。

🎄使用 Scanner 循环读取 N 个数字

import java.util.Scanner;// 需要导入 util 包

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = 0;
        double sum = 0.0;
        while (sc.hasNextDouble()) {
            double ret = sc.nextDouble();
            sum += ret;
            num++;
        }
        System.out.println(sum);
        sc.close();
    }
}

运行结果

🌊hasNextDouble() 的返回值是boolean类型。

💥注意事项:

  • 当循环输入多个数据的时候, IDEA中使用 ctrl + D 来结束循环输入 。

🎄练习:猜数字游戏

import java.util.Random;//使用Random,需要导包
import java.util.Scanner;// 需要导入 util 包

public class TestDemo {
    public static void main(String[] args) {
        Random random = new Random();
        int ran = random.nextInt(100) + 1;
        //random生成的随机数是左闭右开区间,输入100其实就是 0 到 99 --> [ 0 ~100),,如果+1就是1~100 [1~101)
        System.out.println("请输入你要猜的数字");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            int num = scanner.nextInt();
            if (num > ran) {
                System.out.println("你猜的数字太大了");
            } else if (num < ran) {
                System.out.println("你猜的数字太小了");
            } else {
                System.out.println("恭喜你,猜对了");
                break; //猜对了就跳出循环
            }
        }
    }

}

运行结果

 五、总结

举报

相关推荐

0 条评论