Java学习笔记Part09-流程控制

目录

8.流程控制
8.1 流程控制的分类
  • 顺序结构 从上到下一行一行执行
  • 分支结构 根据条件选择不同分支执行
  • 循环结构 需要反复执行的结构

8.2 分支结构-if

if(条件){} 【else if =(条件){}】【else{}】

从上到下挨个检查条件是否成立,如果其中某个条件成立了则执行对应分支代码,其余条件不再判断。

code:

public class code01 {
    public static void func(int a){ 
        if(a%3==0 && a%2==0){
            System.out.println("分支1执行!\n输入的数即是2的倍数也是3的倍数");
        }
        else if (a%2==0){
            System.out.println("分支2执行!\n输入的数是2的倍数!");
        }
        else if(a%3==0){
            System.out.println("分支3执行!\n输入的数是3的倍数");
        }
        else{
            System.out.println("分支4执行!\n输入的数即不是2的倍数也不是3的倍数");
        }
    }
    public static void main(String[] args) {
        func(10);
        func(30);
        func(5);
    }
}

练习:给定月份,输出该月份所在的季节以及该季节的主要活动

code:

public class code02 {
    public static void func(int month){
        if(month < 1 || month > 12){
            System.out.println("输入月份有误");
            return;
        }
        if (3 <= month && month <= 5){
            System.out.println("春季,播种");
        }
        else if(6<= month && month <=8){
            System.out.println("夏季,吃烧烤");
        }
        else if(9<=month && month<=11){
            System.out.println("秋季,秋收");
        }
        else {
            System.out.println("冬季,睡觉");
        }
    }

    public static void main(String[] args) {
        func(2);
        func(5);
        func(7);
        func(9);
    }
}

练习:给定月份和年份 输入当月的天数

code:

public class code03 {
    public static void func(int month,int year){
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
            System.out.println("31天");
        }
        else if(month == 4 || month == 6 || month == 9 || month == 11){
            System.out.println("30天");
        }
        else{
            if (year%4==0){
                System.out.println("29天");
            }
            else{
                System.out.println("28天");
            }
        }
    }

    public static void main(String[] args) {
        func(12,2021);
        func(2,2020);
    }
}

8.3 从键盘录入信息
  1. 导入包:import java.util.Scanner
  2. 创建扫描仪对象:Scanner 扫描仪名 = new Scanner(System.in);
  3. 从键盘录入信息:扫描仪名.next【nextInt,nextDouble.....】();
  4. 释放资源扫描仪名.close()

code:

import java.util.Scanner;
public class code04 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请录入一个整数: ");
        int inputVal = sc.nextInt();
        System.out.println("您输入的是:"+inputVal);
    }
}

8.4 分支语句-switch

switch(变量){ case 变量可能出现的值:{…;break;} case变量可能出现的值:{…;break;} default:{}}

switch中放的变量只能是 **byte short int char String enum **

public class code05 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("输  入  密  码:");
        switch (sc.nextInt()){
            case 114514:{
                System.out.println("哼啊啊啊啊");
                break;
            }
            case 1919810:{
                System.out.println("哼啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊");
                break;
            }
            default:{
                System.out.println("压力马斯内。");
            }
        }
    }
}

8.5 循环结构-while

while(条件){循环体}

先判断条件是否成立,如果成立,那么执行循环体。

执行完循环体再次判断条件是否成立,如果成立继续执行, 知道条件不成立循环结束。

code:

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

练习(使用while循环):

  1. 给定一个整数,输出1~该整数的全部奇数的和。
    (Integer.MIN_VALUE<该整数<Integer.MAX_VALUE)
  2. 给定一个整数,输出1~该整数的所有5的倍数,三个一行。
    (Integer.MIN_VALUE<该整数<Integer.MAX_VALUE)
  3. 从键盘录入任意整数,颠倒输出。
    (Integer.MIN_VALUE<该整数<Integer.MAX_VALUE)
  4. 从键盘录入学生考试的科目和学生的每科分数,输出:总分,最高分,最低分,平均分
  5. 判断一个数是不是水仙花数(水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)。
  6. 输出1~1000的所有水仙花数
  7. 判断一个数是不是素数(素数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。)
  8. 给定一个整数,输出1~该整数的所有素数,每行三个
    (Integer.MIN_VALUE<该整数<Integer.MAX_VALUE)

code:

import java.util.Scanner;
public class code07 {
    private static int input(){
        Scanner sc = new Scanner(System.in);;
        int res = sc.nextInt();
        return res;
    }

    private static void func1(int inputV){
        int _inputV = inputV;
        if(inputV == 0){
            System.out.println("输入为0");
            return;
        }
        if(inputV < 0){
            inputV -= inputV<<1;
        }
        int i= 1;
        long res = 0L;
        while(i <= inputV){
            if (i % 2 != 0){
                if(_inputV>0){
                    res += i;
                }
                else if(_inputV<0){
                    res -= i;
                }
            }
            i++;
        }
        System.out.println("1到"+_inputV+"的全部奇数的和是"+(long)res);
    }
    
    private static void func2(int inputV){
        int _inputV = inputV;
        if(inputV == 0){
            System.out.println("输入为0");
            return;
        }
        if(inputV < 0){
            inputV -= inputV<<1;
        }
        System.out.println("从1到"+_inputV+"的全部5的倍数为:");
        int i = 1, j = 1;
        while (i <= inputV){
            if(j>3){
                j = 1;
                System.out.print("\n");
            }
            if (i%5 == 0){
                System.out.print((_inputV<0?"-":"") + i+"\t");
                j++;
            }
            i++;
        }
    }

    private static void func3(int inputV){
        int _inputV = inputV;
        if(inputV == 0){
            System.out.println("输入为0");
            return;
        }
        if(inputV < 0){
            inputV -= inputV<<1;
            System.out.print("-");
        }
        //检测位数
        int a = inputV, b = 1000000000, c = 11;//c就是位数
        while(a == inputV){
            a = inputV % b;
            b /= 10;
            c--;
        }
        int i = 1;
        c--;
        int _c = c;
        while (i <= (int) Math.pow(10,_c)){
            c = _c;
            int temp = inputV;
            temp /= i;
            while(temp>=10){
                int x =  (int)Math.pow(10,c--);
                temp %= x;
            }
            System.out.print(temp);
            i*=10;
        }
    }

    private static void func4(){
        System.out.print("输入英语成绩:");
        int eS = input();
        System.out.print("输入语文成绩:");
        int cS = input();
        System.out.print("输入数学成绩:");
        int mS = input();
        System.out.println("本次考试总分"+(eS+cS+mS)+"分");
        System.out.println("最高分为"+((eS>cS?eS:cS)>mS?(eS>cS?eS:cS):mS)+"分");
        System.out.println("最低分为"+((eS<cS?eS:cS)<mS?(eS<cS?eS:cS):mS)+"分");
        System.out.println("本次考试平均成绩"+(eS+cS+mS)/3+"分");
    }

    private static boolean func5(int inputV){
        if (inputV > 999 || inputV <100){
            return false;
        }

        if ((Math.pow((inputV/100%10),3))+(Math.pow((inputV/10%10),3))+(Math.pow((inputV/1%100%10),3)) == inputV){
            return true;
        }
        return false;
    }

    private static void func6(){
        System.out.println("100~1000的全部水仙花数:");
        int i = 100;
        while(i<=1000){
            if(func5(i)){
                System.out.println(i);
            }
            i++;
        }
    }

    private static boolean func7(int inputV){
        if (inputV < 1){
            return false;
        }
        int i = 2;
        while (i < inputV){
            if (inputV%i == 0){
                return false;
            }
            i++;
        }
        return true;
    }

    private static void func8(int inputV){
        if (inputV < 1){
            System.out.println("输入小于1");
            return;
        }
        System.out.println("1到"+inputV+"的所有质数:");
        int i = 1, j = 1;
        while (i <= inputV){
            if(j>3){
                j = 1;
                System.out.print("\n");
            }
            if (func7(i)){
                System.out.print(i+"\t");
                j++;
            }
            i++;
        }
    }

    public static void main(String[] args) {
//      func1(input());
//      func2(input());
//      func3(input());
//      func4();
//      System.out.println(func5(input())?"是水仙花数":"不是水仙花数");
//      func6();
//      System.out.println(func7(input())?"是素数":"不是素数");
//      func8(input());
    }
}

8.6 生成随机数

Math.random(),

(int)Math.random()*x+y生成范围:y~(x+y-1)

练习:

模拟回合制打怪游戏

玩家 血值315

怪物 血值500

玩家和怪物互砍

玩家每次攻击怪物产生5-8点伤害

怪物每次攻击玩家产生3-5点伤害

采用回合制 一方挂掉 游戏结束

用程序模拟战斗过程

code:

public class code08 {
    private static int randInt(int min, int max){
        return (int) (Math.random() * (max - min)) +min;
    }
    public static void main(String[] args) {
        int time = 0;
        int pHP = 315;
        int mHP = 500;
        while (true){
            System.out.println("-----------第"+(++time)+"回合------------");

            //玩家攻击
            int pDamage = randInt(5,8);
            System.out.println("玩家攻击!造成了"+pDamage+"点伤害!");
            mHP -= pDamage;
            //检测怪物是否挂掉
            if (mHP <= 0){
                System.out.println("怪物挂掉,游戏结束!") ;
                break;
            }

            //怪物攻击
            int mDamage = randInt(3,5);
            System.out.println("怪物攻击!造成了"+mDamage+"点伤害!");
            pHP -= mDamage;
            //检测玩家是否挂掉
            if (pHP <= 0){
                System.out.println("玩家挂掉,游戏结束!") ;
                break;
            }
        }
    }
}

8.7 循环的嵌套

循环是可以嵌套的。

练习:

一百担粮食 用一百匹马一次运走

大马 一次驼 4担粮食

中型马 一次驼 2担粮食

小型马 两匹驼1担粮食

问 三种马各有多少匹

code:

public class code09 {
    public static void main(String[] args) {
        int ct = 0; //calculate time
        int bNum = 1; //big horse number
        while (bNum < 25) { //大马最多25只
            int mNum = 1; //medium horse number
            while (mNum<50){ //中马最多50只
                ct++;//计算了一次
                //小马个数 = 总马数-大马数-中马数
                int lNum = 100-bNum-mNum; //little horse number
                /*如果大马数*4(大马运量)+中马*2(中马运量)+小马/2(小马运量)=100(总运量)
                 且小马个数为偶数(因为两只小马才能驼一担粮食,则视为满足条件*/
                if (bNum*4+mNum*2+lNum/2 == 100 && lNum%2==0){
                    System.out.println("共有"+bNum+"匹大马,"+mNum+"匹中马"+lNum+"匹小马。");
                    break;
                }
                mNum++;
            }
            bNum++;
        }
        System.out.println("共计算了"+ct+"次");
    }
}

8.8 循环结构-do while

do{ 循环体 }while(条件);

while循环是先判断条件是否成立,如果成立执行循环体;而do while循环是先执行循环体,再判断条件是否成立。结论:无论条件是否成立,循环体至少执行一次。

code:

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

练习:给定任意正整数,倒序输出。

code:

import java.util.Scanner;
public class code11 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        do{
            System.out.print(num%10);
            num /= 10;
        }while (num!=0);
    }
}

8.9 循环结构-for

for(初始值; 循环条件; 迭代)【初始值,循环条件和迭代都可以放在小括号中,也都可以不放在小括号中】

如果初始值放在for循环之外,那么初始值使用范围比较大,在for循环之外仍然可以使用,
如果初始值放在for循环之内,那么初始值使用范围比较小,只能在当前for循环内使用。

迭代如果放在for循环体中,可以由我们自己决定什么时候执行迭代,
如果迭代放在for循环的小括号中,那么意味着迭代在循环体的最后一行执行。

for循环可能比while更常用(
因为for循环可以控制初始变量为内部的局部变量,所以它更符合高内聚,低耦合的程序设计原则。
高内聚:程序的模块内部链接可以特别紧密(越紧密越好
低耦合:程序的模块和模块之间的关联越简单越好

练习:

  1. 输入x,打印一个x*x的直角三角形(x>0)
  2. 打印九九乘法表
  3. 输入x,打印一个x*x的平行四边形(x>0)
  4. 输入x,打印一个x*x的等腰三角形
  5. 输入x,打印一个上底为x,下底为y的等腰梯形
  6. 输入x,输出x的阶乘(x>0)
  7. 输入x,y,求x的y次方
  8. 棋盘上的麦粒问题
    棋盘16格,第一个格子上放一个麦粒,之后每一个格子上的麦粒个数都是上一个格子麦粒个数的两倍,每个麦粒0.0001克,求麦粒总重量。(保留3位小数)
  9. 模拟密码验证问题
    从键盘录入六位密码,验证密码是不是六位,如果不是六位,提示用户重新录入,直到录入的是六位为止。
    校验密码是否正确,三次以内输入密码正确显示欢迎,不正确显示密码错误。
import java.util.Scanner;
public class code12 {
    private static int input(){
        Scanner sc = new Scanner(System.in);;
        int res = sc.nextInt();
        return res;
    }

    private static void func1(int x){
        for (int i = 0; i < x; i++){
            for (int j = 0; j < i; j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }

    private static void func2(){
        for (int i = 1; i <= 9; i++){
            for (int j = 1; j <= i; j++){
                System.out.print(i+"×"+j+"="+i*j+"\t");
            }
            System.out.println();
        }
    }

    private static void func3(int x){
        for (int i = x; i > 0;){
            i--;
            for (int _i = i; _i > 0; _i--){
                System.out.print(" ");
            }
            for (int _i = 0; _i < x; _i++){
                System.out.print("*");
            }
            System.out.println();
        }
    }

    private static void func4(int x){
        for (int i = 0; i < x;){
            int printNum = i+(++i);
            int spaceNum = x-(printNum)/2;
            for (int _i = 0; _i < spaceNum; _i++){
                System.out.print(" ");
            }
            for (int _i = 0; _i < printNum; _i++){
                System.out.print("*");
            }
            System.out.println();
        }
    }

    private static void func5(int x, int y){
        for (int i = 0 ; i < (x>y?x-y:y-x)-1; i++){
            for (int _i = 0; _i < x-((x<y?x:y) + i*2)/2; _i++){
                System.out.print(" ");
            }
            for (int _i = 0; _i < (x<y?x:y) + i*2; _i++){
                System.out.print("*");
            }
            System.out.println();

        }
    }

    private static void func6(int x){
        int res = x--;
        System.out.print(res);
        for (int i = x; i > 0; i--){
            System.out.print("×"+i);
            res *= i;
        }
        System.out.println("="+res);
    }

    private static void func7(int x, int y){
        int _x = x;
        for (int i = 0; i < y; i++){
            x *= _x;
        }
        System.out.println(x);
    }

    private static void func8(){
        int p = 1;
        long sum = 1L;
        for (int i = 0; i < 15; i++){
            p *= 2;
            sum += p;
        }
        System.out.println("麦粒共"+String.format("%.3f",sum*0.0001)+"克。");
    }

    private static void func9(int key){
        int pswd = input();
        while (pswd < 100000 || pswd >999999){
            System.out.println("请输入六位数密码");
            pswd=input();
        }
        for (int i = 2; i > 0; i--){
            if (pswd == key){
                System.out.println("欢迎。");
                return;
            }
            else {
                System.out.println("输入错误,请重新输入。还可以尝试"+i+"次。");
                pswd = input();
                while (pswd < 100000 || pswd >999999){
                    System.out.println("请输入六位数密码");
                    pswd=input();
                }
            }
        }
        System.out.println("尝试次数过多,吞卡。");

    }
    public static void main(String[] args) {
//        func1(input());
//        func2();
//        func3(input());
//        func4(input());
//        func5(input(),input());
//        func6(input());
//        func7(input(),input());
//        func8();
//        func9(114514);
    }
}

8.10 循环控制关键字

break continue return

  • break可以停止循环继续执行,但只能停止最内层的循环,如果想要停止外层循环,那么需要给外层做标记。
  • continue可以停止当前循环执行一次,循环从下一次继续执行
  • return可以停止当前的方法,回到主调方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值