JAVA 流程控制语句 顺序结构分支语句 (接上一节)

案例:只能使用 if-else

从键盘输入一个整数,判断是正数、负数、还是零。

import java.util.Scanner;

public class IfOrSwitchDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("请输入整数:");
        int num = input.nextInt();

        if (num > 0) {
            System.out.println(num + "是正整数");
        } else if (num < 0) {
            System.out.println(num + "是负整数");
        } else {
            System.out.println(num + "是零");
        }

        input.close();
    }
}
2.2.5 练习

练习1:从键盘输入星期的整数值,输出星期的英文单词

import java.util.Scanner;

public class SwitchCaseExer1 {
    public static void main(String[] args) {
        //定义指定的星期
        Scanner input = new Scanner(System.in);
        System.out.print("请输入星期值:");
        int weekday = input.nextInt();

        //switch语句实现选择
        switch(weekday) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("你输入的星期值有误!");
                break;
        }

        input.close();
    }
}

练习2: 使用 switch 把小写类型的 char型转为大写。只转换 a, b, c, d, e. 其它的输出 “other”。

public class SwitchCaseExer2 {

    public static void main(String[] args) {

        char word = 'c';
        switch (word) {
            case 'a':
                System.out.println("A");
                break;
            case 'b':
                System.out.println("B");
                break;
            case 'c':
                System.out.println("C");
                break;
            case 'd':
                System.out.println("D");
                break;
            case 'e':
                System.out.println("E");
                break;
            default :
                System.out.println("other");
        }
    }
}

练习3:

编写一个程序,为一个给定的年份找出其对应的中国生肖。中国的生肖基于12年一个周期,每年用一个动物代表:rat、ox、tiger、rabbit、dragon、snake、horse、sheep、monkey、rooster、dog、pig。

提示:2022年:虎   2022 % 12 == 6 

public class SwitchCaseExer4 {
    public static void main(String[] args){
        //从键盘输入一个年份
        Scanner input = new Scanner(System.in);
        System.out.print("请输入年份:");
        int year = input.nextInt();
        input.close();

        //判断
        switch(year % 12){
            case 0:
                System.out.println(year + "是猴年");
                break;
            case 1:
                System.out.println(year + "是鸡年");
                break;
            case 2:
                System.out.println(year + "是狗年");
                break;
            case 3:
                System.out.println(year + "是猪年");
                break;
            case 4:
                System.out.println(year + "是鼠年");
                break;
            case 5:
                System.out.println(year + "是牛年");
                break;
            case 6:
                System.out.println(year + "是虎年");
                break;
            case 7:
                System.out.println(year + "是兔年");
                break;
            case 8:
                System.out.println(year + "是龙年");
                break;
            case 9:
                System.out.println(year + "是蛇年");
                break;
            case 10:
                System.out.println(year + "是马年");
                break;
            case 11:
                System.out.println(year + "是羊年");
                break;
            default:
                System.out.println(year + "输入错误");
        }
    }
}

练习4:押宝游戏

随机产生3个1-6的整数,如果三个数相等,那么称为“豹子”,如果三个数之和大于9,称为“大”,如果三个数之和小于等于9,称为“小”,用户从键盘输入押的是“豹子”、“大”、“小”,并判断是否猜对了

提示:随机数  Math.random()产生 [0,1)范围内的小数
     如何获取[a,b]范围内的随机整数呢?(int)(Math.random() * (b - a + 1)) + a

import java.util.Scanner;

public class SwitchCaseExer5 {
    public static void main(String[] args) {
        //1、随机产生3个1-6的整数
        int a = (int)(Math.random()*6 + 1);
        int b = (int)(Math.random()*6 + 1);
        int c = (int)(Math.random()*6 + 1);

        //2、押宝
        Scanner input = new Scanner(System.in);
        System.out.print("请押宝(豹子、大、小):");
        String ya = input.next();
        input.close();

        //3、判断结果
        boolean result = false;
        //switch支持String类型
        switch (ya){
            case "豹子": result = a == b && b == c; break;
            case "大": result = a + b + c > 9; break;
            case "小": result = a + b + c <= 9; break;
            default:System.out.println("输入有误!");
        }

        System.out.println("a,b,c分别是:" + a +"," + b +"," + c );
        System.out.println(result ? "猜中了" : "猜错了");
    }
}

3. 循环语句

理解:循环语句具有在某些条件满足的情况下,反复执行特定代码的功能。

循环结构分类:

  • for 循环

  • while 循环

  • do-while 循环

循环结构四要素

  • 初始化部分

  • 循环条件部分

  • 循环体部分

  • 迭代部分

  • 3.1 for循环

  • 3.1.1 基本语法
  • 语法格式:
  • for (①初始化部分; ②循环条件部分; ④迭代部分){
             	③循环体部分;
    }

    执行过程:①-②-③-④-②-③-④-②-③-④-.....-②

  • 说明:

  • for(;;)中的两个;不能多也不能少

  • ①初始化部分可以声明多个变量,但必须是同一个类型,用逗号分隔

  • ②循环条件部分为boolean类型表达式,当值为false时,退出循环

  • ④可以有多个变量更新,用逗号分隔

  • 3.1.2 应用举例
  • 案例1:使用for循环重复执行某些语句

    题目:输出5行HelloWorld

    for(int i = 1;i <= 5;i++){
    			System.out.println("Hello World!");
    		}

    案例2:格式的多样性

  • 题目:写出输出的结果

    public class ForTest2 {
    	public static void main(String[] args) {
            int num = 1;
            for(System.out.print("a");num < 3;System.out.print("c"),num++){
                System.out.print("b");
    
            }
        }
    }
    //abcbc

    案例3:累加的思想

    题目:遍历1-100以内的偶数,并获取偶数的个数,获取所有的偶数的和

  • public class ForTest3 {
    	public static void main(String[] args) {
            int count = 0;//记录偶数的个数
            int sum = 0;//记录偶数的和
      
            for(int i = 1;i <= 100;i++){
    
                if(i % 2 == 0){
                    System.out.println(i);
                    count++;//写在循环体外
                    sum += i;
                }	
    
                //System.out.println("偶数的个数为:" + count);
            }
    
            System.out.println("偶数的个数为:" + count);	
            System.out.println("偶数的总和为:" + sum);
        }
    }

    案例4:结合分支结构使用

  • 题目:输出所有的水仙花数,所谓水仙花数是指一个3位数,其各个位上数字立方和等于其本身。例如: 153 = 1*1*1 + 3*3*3 + 5*5*5

  • public class ForTest4 {
    	public static void main(String[] args) {
    		//定义统计变量,初始化值是0
    		int count = 0;
    		
    		//获取三位数,用for循环实现
    		for(int x = 100; x < 1000; x++) {
    			//获取三位数的个位,十位,百位
    			int ge = x % 10;
    			int shi = x / 10 % 10;
    			int bai = x / 100;
    			
    			//判断这个三位数是否是水仙花数,如果是,统计变量++
    			if((ge*ge*ge+shi*shi*shi+bai*bai*bai) == x) {
                    System.out.println("水仙花数:" + x);
    				count++;
    			}
    		}
    		
    		//输出统计结果就可以了
    		System.out.println("水仙花数共有"+count+"个");
    	}
    }

    案例5:结合break的使用

    说明:输入两个正整数m和n,求其最大公约数和最小公倍数。

    比如:12和20的最大公约数是4,最小公倍数是60。

  • public class ForTest5 {
        public static void main(String[] args) {
            //需求1:最大公约数
            int m = 12, n = 20;
            //取出两个数中的较小值
            int min = (m < n) ? m : n;
    
            for (int i = min; i >= 1; i--) {//for(int i = 1;i <= min;i++){
    
                if (m % i == 0 && n % i == 0) {
                    System.out.println("最大公约数是:" + i); //公约数
    
                    break; //跳出当前循环结构
                }
            }
    
    
            //需求2:最小公倍数
            //取出两个数中的较大值
            int max = (m > n) ? m : n;
    
            for (int i = max; i <= m * n; i++) {
    
                if (i % m == 0 && i % n == 0) {
    
                    System.out.println("最小公倍数是:" + i);//公倍数
    
                    break;
                }
            }
    
        }
    }

    说明:

    1、我们可以在循环中使用break。一旦执行break,就跳出当前循环结构。

    2、小结:如何结束一个循环结构?

    结束情况1:循环结构中的循环条件部分返回false(插个旗子)

    结束情况2:循环结构中执行了break。

    3、如果一个循环结构不能结束,那就是一个死循环!我们开发中要避免出现死循环。

  • 3.1.3 练习

    练习1:打印1~100之间所有奇数的和

  • public class ForExer1 {
    
        public static void main(String[] args) {
    
            int sum = 0;//记录奇数的和
            for (int i = 1; i < 100; i++) {
                if(i % 2 != 0){
                    sum += i;
                }
            }
            System.out.println("奇数总和为:" + sum);
        }
    }

    练习2:

    编写程序从1循环到150,并在每行打印一个值,另外在每个3的倍数行上打印出“foo”,在每个5的倍数行上打印“biz”,在每个7的倍数行上打印输出“baz”。

  • public class ForExer3 {
    
        public static void main(String[] args) {
    
            for (int i = 1; i < 150; i++) {
                System.out.print(i + "\t");
                if(i % 3 == 0){
                    System.out.print("foo\t");
                }
                if(i % 5 == 0){
                    System.out.print("biz\t");
                }
                if(i % 7 == 0){
                    System.out.print("baz\t");
                }
    
                System.out.println();
            }
        }
    }

    3.2 while循环

    3.2.1 基本语法
  • 语法格式:
    ①初始化部分
    while(②循环条件部分){
        ③循环体部分;
        ④迭代部分;
    }

    执行过程:①-②-③-④-②-③-④-②-③-④-...-②

  • 说明:

  • while(循环条件)中循环条件必须是boolean类型。

  • 注意不要忘记声明④迭代部分。否则,循环将不能结束,变成死循环。

  • for循环和while循环可以相互转换。二者没有性能上的差别。实际开发中,根据具体结构的情况,选择哪个格式更合适、美观。

  • for循环与while循环的区别:初始化条件部分的作用域不同。while循环中初始化条件在while循环结束后,依然有效。

  • 3.2.2 应用举例

    案例1:输出5行HelloWorld!

  • class WhileTest1 {
    	public static void main(String[] args) {
    		
    		int i = 1;
    		while(i <= 5){
    			System.out.println("Hello World!");
    			i++;
    		}
    	}
    }

    案例2:遍历1-100的偶数,并计算所有偶数的和、偶数的个数(累加的思想)

  • class WhileTest2 {
    	public static void main(String[] args) {
    		//遍历1-100的偶数,并计算所有偶数的和、偶数的个数(累加的思想)
    		int num = 1;
    
    		int sum = 0;//记录1-100所有的偶数的和
    		int count = 0;//记录1-100之间偶数的个数
    
    		while(num <= 100){
    			
    			if(num % 2 == 0){
    				System.out.println(num);
    				sum += num;
    				count++;
    			}
    			
    			//迭代条件
    			num++;
    		}
    	
    		System.out.println("偶数的总和为:" + sum);
    		System.out.println("偶数的个数为:" + count);
    	}
    }

    案例3:猜数字游戏

  • 随机生成一个100以内的数,猜这个随机数是多少?

    从键盘输入数,如果大了,提示大了;如果小了,提示小了;如果对了,就不再猜了,并统计一共猜了多少次。

    提示:生成一个[a,b] 范围的随机数的方式:(int)(Math.random() * (b - a + 1) + a)

  • public class GuessNumber {
        public static void main(String[] args) {
            //获取一个随机数
            int random = (int) (Math.random() * 100) + 1;
    
            //记录猜的次数
            int count = 1;
    
            //实例化Scanner
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入一个整数(1-100):");
            int guess = scan.nextInt();
    
            while (guess != random) {
    
                if (guess > random) {
                    System.out.println("猜大了");
                } else if (guess < random) {
                    System.out.println("猜小了");
                }
    
                System.out.println("请输入一个整数(1-100):");
                guess = scan.nextInt();
    			//累加猜的次数
                count++;
    
            }
    
            System.out.println("猜中了!");
            System.out.println("一共猜了" + count + "次");
        }
    }

    案例4:折纸珠穆朗玛峰

  • 世界最高山峰是珠穆朗玛峰,它的高度是8848.86米,假如我有一张足够大的纸,它的厚度是0.1毫米。
    请问,我折叠多少次,可以折成珠穆朗玛峰的高度?

  • public class ZFTest {
        public static void main(String[] args) {
            //定义一个计数器,初始值为0
            int count = 0;
    
            //定义珠穆朗玛峰的高度
            int zf = 8848860;//单位:毫米
    
            double paper = 0.1;//单位:毫米
    
            while(paper < zf){
                //在循环中执行累加,对应折叠了多少次
                count++;
                paper *= 2;//循环的执行过程中每次纸张折叠,纸张的厚度要加倍
            }
    
            //打印计数器的值
            System.out.println("需要折叠:" + count + "次");
            System.out.println("折纸的高度为" + paper/1000 + "米,超过了珠峰的高度");
        }
    }
    3.2.3 练习
  • 练习:从键盘输入整数,输入0结束,统计输入的正数、负数的个数。
  • import java.util.Scanner;
    
    public class Test05While {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
    
            int positive = 0; //记录正数的个数
            int negative = 0;  //记录负数的个数
            int num = 1; //初始化为特殊值,使得第一次循环条件成立
            while(num != 0){
                System.out.print("请输入整数(0表示结束):");
                num = input.nextInt();
    
                if(num > 0){
                    positive++;
                }else if(num < 0){
                    negative++;
                }
            }
            System.out.println("正数个数:" + positive);
            System.out.println("负数个数:" + negative);
    
            input.close();
        }
    }
    

    3.3 do-while循环

  • 3.3.1 基本语法
    语法格式:
    ①初始化部分;
    do{
    	③循环体部分
    	④迭代部分
    }while(②循环条件部分); 

    执行过程:①-③-④-②-③-④-②-③-④-...-②

  • 说明:

  • 结尾while(循环条件)中循环条件必须是boolean类型

  • do{}while();最后有一个分号

  • do-while结构的循环体语句是至少会执行一次(先执行再循环),这个和for和while是不一样的

  • 循环的三个结构for、while、do-while三者是可以相互转换的。(do-while应用较少)

3.3.2 应用举例

案例1:遍历1-100的偶数,并计算所有偶数的和、偶数的个数(累加的思想)

class DoWhileTest1 {
	public static void main(String[] args) {

		//遍历1-100的偶数,并计算所有偶数的和、偶数的个数(累加的思想)
		//初始化部分
		int num = 1;
		
		int sum = 0;//记录1-100所有的偶数的和
		int count = 0;//记录1-100之间偶数的个数

		do{
			//循环体部分
			if(num % 2 == 0){
				System.out.println(num);
				sum += num;
				count++;
			}
			
			num++;//迭代部分


		}while(num <= 100); //循环条件部分


		System.out.println("偶数的总和为:" + sum);
		System.out.println("偶数的个数为:" + count);
	}
}

案例2:体会do-while至少会执行一次循环体

class DoWhileTest2 {
	public static void main(String[] args) {
        //while循环:   //无输出
		int num1 = 10;
		while(num1 > 10){
			System.out.println("hello:while");
			num1--;
		}

		//do-while循环:  //输出hello
		int num2 = 10;
		do{
			System.out.println("hello:do-while");
			num2--;
		}while(num2 > 10);

	}
}

案例3:ATM取款

声明变量balance并初始化为0,用以表示银行账户的余额,下面通过ATM机程序实现存款,取款等功能。

=========ATM========
   1、存款
   2、取款
   3、显示余额
   4、退出
请选择(1-4):

①do while循环

import java.util.Scanner;
public class ATM {
	public static void main(String[] args) {
		//初始化条件
		double balance = 0.0;//表示银行账户的余额
		Scanner scan = new Scanner(System.in);
		boolean isFlag = true;//用于控制循环的结束
		do{
			System.out.println("=========ATM========");
			System.out.println("\t1、存款");
			System.out.println("\t2、取款");
			System.out.println("\t3、显示余额");
			System.out.println("\t4、退出");
			System.out.print("请选择(1-4):");

			int selection = scan.nextInt();
			
			switch(selection){
				case 1:
					System.out.print("要存款的额度为:");
					double addMoney = scan.nextDouble();
					if(addMoney > 0){
						balance += addMoney;
					}
					break;
				case 2:
					System.out.print("要取款的额度为:");
					double minusMoney = scan.nextDouble();
					if(minusMoney > 0 && balance >= minusMoney){
						balance -= minusMoney;
					}else{
						System.out.println("您输入的数据非法或余额不足");
					}
					break;
				case 3:
					System.out.println("当前的余额为:" + balance);
					break;
				case 4:
					System.out.println("欢迎下次进入此系统。^_^");
					isFlag = false;
					break;
				default:
					System.out.println("请重新选择!");
					break;	
			}
		
		}while(isFlag);

		//资源关闭
		scan.close();
		
	}
}

②while循环

double balance = 0.0;//表示银行账户的余额
        Scanner atm = new Scanner(System.in);
        boolean isFlag=true;
        while (isFlag){
            System.out.println("=========ATM========");
            System.out.println("\t1、存款");
            System.out.println("\t2、取款");
            System.out.println("\t3、显示余额");
            System.out.println("\t4、退出");
            System.out.print("请选择(1-4):");
            int xuan=atm.nextInt();
            switch (xuan){
                case 1:
                    System.out.println("请输入要存的金额");
                    double addMoney=atm.nextDouble();
                    if(addMoney > 0){
                        balance += addMoney;
                    }
                    break;
                case 2:
                    System.out.println("请输入要取的金额");
                    double lowMoney=atm.nextDouble();
                    if(lowMoney > 0&&lowMoney<=balance){
                        balance -= lowMoney;
                    }
                    else {
                        System.out.println("您输入的数据非法或余额不足");
                    }
                    break;
                case 3:
                    System.out.println("您的金额是"+balance);
                    break;
                case 4:
                    System.out.println("谢谢使用");
                    isFlag=false;
                    break;
                default:
                    System.out.println("请重新选择!");
                    break;
            }
        }
3.3.3 练习

练习1:随机生成一个100以内的数,猜这个随机数是多少?

从键盘输入数,如果大了提示,大了;如果小了,提示小了;如果对了,就不再猜了,并统计一共猜了多少次。

import java.util.Scanner;

public class DoWhileExer {
    public static void main(String[] args) {
        //随机生成一个100以内的整数
		/*
		Math.random() ==> [0,1)的小数
		Math.random()* 100 ==> [0,100)的小数
		(int)(Math.random()* 100) ==> [0,100)的整数
		*/
        int num = (int)(Math.random()* 100);
        //System.out.println(num);

        //声明一个变量,用来存储猜的次数
        int count = 0;

        Scanner input = new Scanner(System.in);
        int guess;//提升作用域
        do{
            System.out.print("请输入100以内的整数:");
            guess = input.nextInt();

            //输入一次,就表示猜了一次
            count++;

            if(guess > num){
                System.out.println("大了");
            }else if(guess < num){
                System.out.println("小了");
            }
        }while(num != guess);

        System.out.println("一共猜了:" + count+"次");

        input.close();
    }
}

3.4 对比三种循环结构

三种循环结构都具有四个要素:

  • 循环变量的初始化条件

  • 循环条件

  • 循环体语句块

  • 循环变量的修改的迭代表达式

从循环次数角度分析

例如:两个for嵌套循环格式设外层循环次数为m次,内层为n次,则内层循环体实际上需要执行m*n次。

  • do-while循环至少执行一次循环体语句。

  • for和while循环先判断循环条件语句是否成立,然后决定是否执行循环体。

  • 如何选择

  • 遍历有明显的循环次数(范围)的需求,选择for循环

  • 遍历没有明显的循环次数(范围)的需求,选择while循环

  • 如果循环体语句块至少执行一次,可以考虑使用do-while循环

  • 本质上:三种循环之间完全可以互相转换,都能实现循环的功能

  • 3.5 "无限"循环

  • 3.5.1 基本语法

    语法格式:

  • 最简单"无限"循环格式:while(true)for(;;)

  • 适用场景:

  • 开发中,有时并不确定需要循环多少次,需要根据循环体内部某些条件,来控制循环的结束(

    public class EndlessFor2 {
        public static void main(String[] args) {
            for (; true;){ //条件永远成立,死循环
                System.out.println("我爱你!");
            }
        }
    }

    使用break)。

  • 死循环后面不能有执行语句

  • 如果此循环结构不能终止,则构成了死循环!开发中要避免出现死循环。

  • 3.5.2 应用举例

    案例1:实现爱你到永远...

  • public class EndlessFor1 {
        public static void main(String[] args) {
            for (;;){
                System.out.println("我爱你!");
            }
    //        System.out.println("end");//永远无法到达的语句,编译报错
        }
    }
    public class EndlessFor2 {
        public static void main(String[] args) {
            for (; true;){ //条件永远成立,死循环
                System.out.println("我爱你!");
            }
        }
    }
    public class EndlessFor3 {
        public static void main(String[] args) {
            for (int i=1; i<=10; ){ //循环变量没有修改,条件永远成立,死循环
                System.out.println("我爱你!");
            }
        }
    }

    案例2:从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。

  • import java.util.Scanner;
    
    class PositiveNegative {
    	public static void main(String[] args) {
    		Scanner scanner = new Scanner(System.in);
            
    		int positiveNumber = 0;//统计正数的个数
    		int negativeNumber = 0;//统计负数的个数
    		for(;;){  //while(true){
    			System.out.println("请输入一个整数:(输入为0时结束程序)");
    			int num = scanner.nextInt();
    			if(num > 0){
    				 positiveNumber++;
                }else if(num < 0){
    				 negativeNumber++;
            	}else{
                    System.out.println("程序结束");
    				break; 
                }
             }
    		 System.out.println("正数的个数为:"+ positiveNumber);
    		 System.out.println("负数的个数为:"+ negativeNumber);  
            
             scanner.close();
    	} 
    }
    

    3.6 嵌套循环(或多重循环)

    3.6.1 使用说明
  • 所谓嵌套循环,是指一个循环结构A的循环体是另一个循环结构B。比如,for循环里面还有一个for循环,就是嵌套循环。其中,for ,while ,do-while均可以作为外层循环或内层循环。

    • 外层循环:循环结构A

    • 内层循环:循环结构B

  • 实质上,嵌套循环就是把内层循环当成外层循环的循环体。只有当内层循环的循环条件为false时,才会完全跳出内层循环,才可结束外层的当次循环,开始下一次的外层循环。

  • 技巧:从二维图形的角度看,外层循环控制行数,内层循环控制列数

  • 开发经验:实际开发中,我们最多见到的嵌套循环是两层。一般不会出现超过三层的嵌套循环。如果将要出现,一定要停下来重新梳理业务逻辑,重新思考算法的实现,控制在三层以内。否则,可读性会很差。

  • 例如:两个for嵌套循环格式

  • for(初始化语句①; 循环条件语句②; 迭代语句⑦) {
        for(初始化语句③; 循环条件语句④; 迭代语句⑥) {
          	循环体语句⑤;
        }
    }
    
    //执行过程:① - ② - ③ - ④ - ⑤ - ⑥ - ④ - ⑤ - ⑥ - ... - ④ - ⑦ - ② - ③ - ④ - ⑤ - ⑥ - ④..

    执行特点:外层循环执行一次,内层循环执行一轮。

  • 3.6.2 应用举例
  • 案例1:打印5行6个*
  • class ForForTest1 {
    	public static void main(String[] args) {
    		/*
    		
    		******
    		******
    		******
    		******
    		******
    		
    		*/
    		
    		for(int j = 1;j <= 5;j++){
    
    			for(int i = 1;i <= 6;i++){
    				System.out.print("*");
    			}
    			
    			System.out.println();
    		}
        }
    }

    案例2:打印5行直角三角形 //println会换行

                                                //print不换行

  • *
    **
    ***
    ****
    *****

  • public class ForForTest2 {
        public static void main(String[] args){
            for (int i = 1; i <= 5; i++) {
                for (int j = 1; j <= i; j++) {
                    System.out.print("*");
                }
                System.out.println();
            }
        }
    }	
    //i(第几行)
    //j(每一行中*的个数)

    案例3:打印5行倒直角三角形

  • *****
    ****
    ***
    **
    *

  • public class ForForTest3 {
        public static void main(String[] args){
            for(int i = 1;i <= 5;i++){
    			for(int j = 1;j <= 6 - i;j++){
    				System.out.print("*");
    			
    			}
    			System.out.println();
    		
    		}
        }
    }

    案例4:打印"菱形"形状的图案  

  •         * 
          * * * 
        * * * * * 
      * * * * * * * 
    * * * * * * * * * 
      * * * * * * * 
        * * * * * 
          * * * 
            *     

  • public class ForForTest4 {
    
        public static void main(String[] args) {
        /*
            上半部分		i		m(表示-的个数)    n(表示*的个数)关系式:2*i + m = 10 --> m = 10 - 2*i
        --------*		   1	   8			   1							n = 2 * i - 1
        ------* * *		   2	   6			   3
        ----* * * * *	   3	   4			   5
        --* * * * * * *	   4	   2		       7
        * * * * * * * * *  5	   0			   9
    
            下半部分         i      m                n              关系式: m = 2 * i
        --* * * * * * *    1       2                7                     n = 9 - 2 * i
        ----* * * * *      2       4                5
        ------* * *        3       6                3
        --------*          4       8                1
    
                */
            //上半部分
            for (int i = 1; i <= 5; i++) {
                //-
                for (int j = 1; j <= 10 - 2 * i; j++) {
                    System.out.print(" ");
                }
                //*
                for (int k = 1; k <= 2 * i - 1; k++) {
                    System.out.print("* ");
                }
                System.out.println();
            }
            //下半部分
            for (int i = 1; i <= 4; i++) {
                //-
                for (int j = 1; j <= 2 * i; j++) {
                    System.out.print(" ");
                }
    
                //*
                for (int k = 1; k <= 9 - 2 * i; k++) {
                    System.out.print("* ");
                }
                System.out.println();//换行 相当于c中的\n
            }
        }
    
    }

    案例5:九九乘法表

  • public class ForForTest5 {
        public static void main(String[] args) {
            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();
            }
        }
    }

    4. 关键字break和continue的使用

    4.1 break和continue的说明(break使用多于continue)

  •             适用范围            在循环结构中使用的作用                        相同点

    break        switch-case
                循环结构            一旦执行,就结束(或跳出)当前循环结构            此关键字的后面,不能声明语句

    continue    循环结构            一旦执行,就结束(或跳出)当次循环结构            此关键字的后面,不能声明语句

  • 4.2 应用举例

  • class BreakContinueTest1 {
    	public static void main(String[] args) {
    	
    		for(int i = 1;i <= 10;i++){
    			
    			if(i % 4 == 0){
    				//break;//123
    				continue;//123567910
    				//如下的语句不可能被执行,编译不通过
    				//System.out.println("今晚迪丽热巴要约我吃饭");
    			}
    
    			System.out.print(i);
    		}
    
    		System.out.println("####");
    
    		//嵌套循环中的使用
    		for(int i = 1;i <= 4;i++){
    		
    			for(int j = 1;j <= 10;j++){
    				if(j % 4 == 0){
    					//break; //结束的是包裹break关键字的最近的一层循环!
    					continue;//结束的是包裹break关键字的最近的一层循环的当次!
                        		 //123567910
                        		 //123567910
                        		 //123567910
                        		 //123567910
    				}
    				System.out.print(j);
    			}
    			System.out.println();
    		}
    
    	}
    }

    4.3 带标签的使用(了解)

  • continue语句出现在多层嵌套的循环语句体中时,也可以通过标签指明要跳过的是哪一层循环。
  • 标号语句必须紧接在循环的头部。标号语句不能用在非循环语句的前面。
  • 举例:
  • class BreakContinueTest2 {
    	public static void main(String[] args) {
    		l:for(int i = 1;i <= 4;i++){
    		
    			for(int j = 1;j <= 10;j++){
    				if(j % 4 == 0){
    					//break l;
    					continue l;
    				}
    				System.out.print(j);
    			}
    			System.out.println();
    		}
    	}
    }

    4.4 经典案例

    题目:找出100以内所有的素数(质数)?100000以内的呢?

    目的:不同的代码的实现方式,可以效率差别很大。

    分析:素数(质数):只能被1和它本身整除的自然数。 ---> 从2开始,到这个数-1为止,此范围内没有这个数的约数。则此数是一个质数。 比如:2、3、5、7、11、13、17、19、23、...

    for (int q=2;q<=100;q++){
                int num1=0;
                for (int w=2;w<q;w++){
                    if (q%w==0){
                        num1++;
                    }
                }
                if (num1==0){
                    System.out.println(q);
                }
            }

    4.5 练习

  • 生成 1-100 之间的随机数,直到生成了 97 这个数,看看一共用了几次?

    提示:使用 (int)(Math.random() * 100) + 1

  • public class NumberGuessTest {
        public static void main(String[] args) {
            int count = 0;//记录循环的次数(或生成随机数进行比较的次数)
            while(true){
                int random = (int)(Math.random() * 100) + 1;
                count++;
                if(random == 97){
                    break;
                }
            }
    
            System.out.println("直到生成随机数97,一共比较了" + count + "次");
    
        }
    }

    5. Scanner:键盘输入功能的实现

  • 如何从键盘获取不同类型(基本数据类型、String类型)的变量:使用Scanner类。

  • 键盘输入代码的四个步骤:

    1. 导包:import java.util.Scanner;

    2. 创建Scanner类型的对象:Scanner scan = new Scanner(System.in);

    3. 调用Scanner类的相关方法(next() / nextXxx()),来获取指定类型的变量

    4. 释放资源:scan.close();

  • 注意:需要根据相应的方法,来输入指定类型的值。如果输入的数据类型与要求的类型不匹配时,会报异常 导致程序终止。

  • Scanner类中提供了获取byte\short\int\long\float\double\boolean\String类型变量的方法。没有提供获取char类型变量的方法。需要使用next.charAt(0)

  • 5.1 各种类型的数据输入

    案例:小明注册某交友网站,要求录入个人相关信息。如下:

    请输入你的网名、你的年龄、你的体重、你是否单身、你的性别等情况。

  • //① 导包
    import java.util.Scanner;
    
    public class ScannerTest1 {
    
        public static void main(String[] args) {
            //② 创建Scanner的对象
            //Scanner是一个引用数据类型,它的全名称是java.util.Scanner
            //scanner就是一个引用数据类型的变量了,赋给它的值是一个对象(对象的概念我们后面学习,暂时先这么叫)
            //new Scanner(System.in)是一个new表达式,该表达式的结果是一个对象
            //引用数据类型  变量 = 对象;
            //这个等式的意思可以理解为用一个引用数据类型的变量代表一个对象,所以这个变量的名称又称为对象名
            //我们也把scanner变量叫做scanner对象
            Scanner scanner = new Scanner(System.in);//System.in默认代表键盘输入
            
            //③根据提示,调用Scanner的方法,获取不同类型的变量
            System.out.println("欢迎光临你好我好交友网站!");
            System.out.print("请输入你的网名:");
            String name = scanner.next();//字符串类型
    
            System.out.print("请输入你的年龄:");
            int age = scanner.nextInt();//整数类型
    
            System.out.print("请输入你的体重:");
            double weight = scanner.nextDouble();
    
            System.out.print("你是否单身(true/false):");
            boolean isSingle = scanner.nextBoolean();
    
            System.out.print("请输入你的性别:");
            char gender = scanner.next().charAt(0);//先按照字符串接收,然后再取字符串的第一个字符(下标为0)
    
            System.out.println("你的基本情况如下:");
            System.out.println("网名:" + name + "\n年龄:" + age + "\n体重:" + weight + 
                               "\n单身:" + isSingle + "\n性别:" + gender);
            
            //④ 关闭资源
            scanner.close();
        }
    }

    6. 如何获取一个随机数

    如何产生一个指定范围的随机整数?

    1、java提供的API:Math类的random()的调用,会返回一个[0,1)范围的一个double型值

    2、Math.random() * 100 ---> [0,100)

  • (int)(Math.random() * 100) ---> [0,99]

  • (int)(Math.random() * 100) + 5 ----> [5,104]

    3、如何获取[a,b]范围内的随机整数呢?(int)(Math.random() * (b - a + 1)) + a

    a在()内外无区别

    4、举例

  • class MathRandomTest {
    	public static void main(String[] args) {
    		double value = Math.random();
    		System.out.println(value);
    
    		//[1,6]
    		int number = (int)(Math.random() * 6) + 1; //
    		System.out.println(number);
    	}
    }
    

  • 14
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值