Java 基本功02-程序结构的分支与循环

418 阅读9分钟

1. 程序的结构

1.1 顺序

1.1.1 顺序结构:

所谓顺序结构,就最简单的程序结构,也是最常用的程序结构。只要按照解决问题的顺序写出相应的语句就行,它的执行顺序是自上而下,依次执行。

1.2 分支(条件)

1.2.1 if 分支:

语法结构:
	if (判断条件,true and false) {
		代码块;
	}
	
执行流程:
	1、先判断条件的结果
	2、若为 true 则执行代码块,若为 false 则不执行代码块
	
int money = 10;

if (money > 5) {
    System.out.println("我们可以买一辆梅赛德斯~~");
}

1.2.2 if - else 分支:

语法结构:
	if (判断条件, true and false) {
		代码块1;
	} else {
		代码块2;
	}
	
执行流程:
	1、先判断条件的结果
	2、若结果为 true 则执行代码块1,否则执行代码块2
	
int money = 5;

if (money > 10) {
    System.out.println("我们可以买一辆梅赛德斯~~");
} else {
    System.out.println("我们还是去买辣条吧!");
}

1.2.3 if - else if 分支:

语法结构:
	if (判断条件1, true and false) {
		代码块1;
	} else if (判断条件2,true and false) {
		代码块2;
	} else {
		代码块3;
	}
	
执行流程:
	1、先判断条件1,如果为 true 则执行代码块1
	2、如果判断条件1的结果值为 false 则进行判断条件2的结果,如果为 true 则执行代码块2
	3、如果判断条件2的结果为 false 则执行代码块3
		
/*
学生成绩:
	90 ~ 100 秀儿
	80 ~ 90 良儿
	70 ~ 80 中儿
	60 ~ 70 过儿
	60以下 叫你爹穿着特拉板来见我
*/

// 导包,点技能点
import java.util.Scanner;

class Demo {
    
	public static void main(String[] args) {
        
		int score = 0;
        
		// 创建一个Scanner的“变量”
		Scanner sc = new Scanner(System.in);
		System.out.println("亲,请输入一个学生成绩~");
        
		// 从键盘上获取int类型数据保存到score变量
		score = sc.nextInt();
		
		// 用户输入数据合法性判断
		if (score < 0 || score > 100) {
			System.out.println("亲,您输入的数据不对哦~");
			// 退出程序
			System.exit(0);
		}
		
		if (score >= 90) {
			System.out.println("秀儿");
		} else if (score >= 80) {
			System.out.println("良儿");
		} else if (score >= 70) {
			System.out.println("中儿");
		} else if (score >= 60) {
			System.out.println("过儿");
		} else {
			System.out.println("叫你爹穿着特拉板来见我");
		}
	}
} 

1.2.4 switch - case 结构:

语法结构:
	switch (判断条件, true and false) {
		case 常量1:
			处理方式1;
			break;
		case 常量2:
			处理方式2;
			break;
		default:
			最终处理方式;
			break;
	}
	
注意事项:
	1switch case 结构执行的代码是 case/defaultbreak 或者 case/default 到大括号其中的语句
	2break 可以省略,对应 case 语句没有 break 的情况,会继续往下执行
	3switch case 结构中,不允许出现重复的 case 选项
	4default 可以省略,至于省略还是使用,要参考当时的业务逻辑

class Demo {

	public static void main(String[] args) {
	
		int choose = 0;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("客官,您要点点儿啥?");
		System.out.println("1. 烤面筋");
		System.out.println("2. 烤羊肉串");
		System.out.println("3. 烤葱饼");
		System.out.println("4. 烤牛板筋");
		System.out.println("5. 烤鱿鱼");
		
		choose = sc.nextInt();
		
		switch (choose) {
			case 1:
				System.out.println(5);
				break;
			case 2:
				System.out.println(10);
				break;
			case 3:
				System.out.println(15);
				break;
			case 4:
				System.out.println(20);
				break;
			case 5:
				System.out.println(25);
				break;
			 default:
				System.out.println("客官,我们没有这个菜品~");
				break;
		}
	}
}

1.3 循环

1.3.1 为什么要使用循环:

在代码中,一定会出现大量重复的功能,如果使用CV大法,暴力解决问题,会导致以下一些情况:
	1、代码过于臃肿
	2、代码维护性极差
	3、代码阅读性极差

Java 有非常灵活的三种循环机制:
	- while 循环
	- do while 循环
	- for 循环

1.3.2 while 循环:

while循环是一个控制结构,可以重复的特定任务次数。

语法结构:
	while (循环条件) {
		循环体;
		循环条件变更;
	}
	
执行流程:
	当程序执行到 while 循环结构时,首先判断循环条件是否为 true,如果为 true 就执行循环体(循环条件变更),之后再回到循环条件判断,直到循环条件为 false 终止循环!

注意:
	while 循环体中一定要带循环条件变更,否则会死循环!
	终止死循环 Ctrl + C
	
public class Demo{

	public static void main(String[] args){
	
		int i = 1;
		while(i < 4){
			System.out.println("重要的事情说三遍:上课请认真请讲!");
			i ++; // 循环条件变更
		}
		System.out.println(i);
		
		//请循环输出周1到周7
		int w = 1;
		while(w <= 7){
			System.out.println("周" + w);
		}
	}
}

1.3.3 do-while 循环:

语法结构:
	do {
		循环体;
		循环条件变更;
	} while (循环条件);

执行流程:
	当程序执行到 do-while 循环结构时,首先执行循环体(循环条件变更),再判断 while 之后的小括号里面的循环条件是否为 true,如果为 true 继续循环,如果为 false 终止循环!
	
public class Demo{

	public static void main(String[] args){
		
		int i = 1;
		do{
			System.out.println("别睡觉了");
			i ++;
		} while (i <= 3);
	} 
}

1.3.4 whlie 和 do-while 的区别:

1while 循环每一次执行循环体,都是在判断之后执行的
2do-while 循环执行循环体,第一次是没有任何判断的

建议:
	能使用 while 循环,就不要使用 do- while 循环。

1.3.5 for 循环:

for 循环语句是一个循环控制结构,可以执行指定次数的循环。

语法结构:
	for (初始化数据; 循环条件; 循环条件变更) {
		代码块;
	}
	
执行流程:
	1、首先执行初始化数据操作,声明一种类型,可以初始化一个或多个变量。
	2、判断循环条件:
		-如果为 true 执行循环体
		-如果为 false 循环终止,执行循环体后面的语句
	3、执行一次循环后,执行循环条件变更
	4、再次判断循环条件,继续执行循环
	
public class Demo{

	public static void main(String[] args){
	
		// 打印数字 1-10
		int i;
		for(i = 1; i <= 10; i ++){
			System.out.println(i);
		}
	}
}

1.3.6 For-Each 循环(增强for循环):

For-Each循环也叫增强型的for循环,或者叫foreach循环。

For-Each循环是JDK1.5的新特性。

For-Each循环的加入简化了集合的遍历。

语法格式:
	for (数据类型 声明语句 : 表达式) {
		代码块;
	}
	
注意:
	对增强 for 的目标会先进行是否为 null 的判断,所以增强 for 的目标不能为 null
        
public class Demo{

	public static void main(String[] args){
		
		int i = 1;
		do{
			System.out.println("别睡觉了");
			i ++;
		} while (i <= 3);
	} 
}

1.3.7 break 关键字:

break 的适用范围:
	只能适用于 switch 或者是循环语句中
	
break 的作用:
	1breakswitch 语句中的作用是结束一个 switch 语句。
	2break 在循环语句中的作用是结束当前所在的循环语句。

1.3.8 continue 关键字:

适用范围:
	continue 只能用于循环语句。
	
作用:
	continue 的作用是跳过本次的循环体内容,继续下一次循环。
	如果循环体内部 continue 之后没有内容,那么加上 continue 是没有意义的。
	
注意事项:
	1、在一种情况下(顺序执行),continue 后面不能跟有其他语句,因为是永远无法执行到的,所以编译会报错,Java 是不允许出现废话的。
	2continue 也可以配合标记使用。
	3、如果 continue 出现在循环的末尾(最后一句话),那么可以省略。

2. 简单小练习

2.1 展示100以内所有的奇数和偶数

public class TestOneTwo {
    
    public static void main(String[] args) {
        
        for (int num = 0; num <= 100; num++) {
            if (num % 2 == 0) {
                System.out.println("这是偶数:" + num);
            } else {
                System.out.println("这是奇数:" + num);
            }
        } 
    }
}

2.2 计算 1-150 的和

public class TestSum {

    public static void main(String[] args) {

        int sum = 0;
        for (int i = 1; i <= 150; i++) {
            sum = sum + i;
        }

        System.out.println(sum);
    }
}

2.3 逢 7 过

public class TestSeven {

    public static void main(String[] args) {

        int count = 0;
        int j = 1;
        for (int i = 1; i <= 100; i++) {
            // i % 7 != 0 对7的倍数进行判断
            // i / 10 != 7 对十位数含7的数进行判断
            // i % 10 != 7 对个位数是7的数进行判断
            if (i % 7 != 0 && i / 10 != 7 && i % 10 != 7) {
                if (j % 10 == 0) {
                    // 每排显示十个数
                    // 取余是10的倍数输出并换行,也就是逢10就换行
                    System.out.print(i + " ");
                    System.out.println();
                } else {
                    System.out.print(i + " ");
                }
                // 每次循环打印一次和七无关的数字后计数一次
                count++;
            } else {
                if (j % 10 == 0) {
                    System.out.print("过" + " ");
                    System.out.println();
                } else {
                    System.out.print("过" + " ");
                }
            }
            // 每次循环打印一次无论是和七有关的还是无关的数字之后
            // 判断一次一行是否打印够10次,是否换行
            j++;
        }

        System.out.println();
        System.out.println("不是七的倍数也不含七的数有:" + count + "个");
    }
}

2.4 多种方法打印 26 个小写字母

public class TestLowerCase {

    public static void main(String[] args) {

        char ch = 'a';

        // while 循环
        while (ch <= 'z') {
            System.out.print(ch + " ");
            ch += 1;
        }
        System.out.println();

        // do while 循环
        ch = 'a';
        do {
            System.out.print(ch + " ");
            ch += 1;
        } while (ch <= 'z');
        System.out.println();

        // for 循环
        for (ch = 'a'; ch <= 'z'; ch += 1) {
            System.out.print(ch + " ");
        }
    }
}

2.5 输入

例如:
	输入 5 8
    计算 5 + 6 + 7 + 8
    输入 26
    
public class TestImport {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入第一个数字:");
        int num1 =scanner.nextInt();
        System.out.println("请输入第一个数字:");
        int num2 =scanner.nextInt();

        int count = 0;

        // 如果 num1 值小于 num2 值,两个值交换
        if (num1 > num2) {
            int temp = num2;
            num2 = num1;
            num1 = temp;
        }
        for (int i = num1; i <= num2; i++) {
            count += i;
            if (i < num2 - 1) {
                System.out.print(i + " + ");
            } else if (i == num2 -1) {
                System.out.print(i);
            } else {
                System.out.print(" + " + i + " = " + count);
            }
        }
    }
}

2.6 整数逆序输出, 例如输入一个整数 12345,输出 54321

public class TestReverse {

    public static void main(String[] args) {

        int num = 147258369;

        while (num > 0) {
            System.out.println(num % 10);
            // num /= 10 --> num = num / 10
            num /= 10;
        }
        
        // i /= 10 --> i = i / 10
        for (int i = num; i > 0; i /= 10) {
            System.out.println(i % 10);
        }
    }
}

2.7 输出图形 1

/*
   *****
   *****
   *****
   *****
   *****
 */

public class TestStarFive {

    public static void main(String[] args) {

        // 无脑打印
        System.out.println("*****");
        System.out.println("*****");
        System.out.println("*****");
        System.out.println("*****");
        System.out.println("*****");

        System.out.println("------分------割------线------");

        // 利用循环
        // 外层控制总行数
        for (int i = 1; i <= 5 ; i++) {
            // 内层控制每一行的个数
            for (int j = 1; j <= 5; j++) {
                System.out.print("*");
            }

            System.out.println();
        }
    }
}

2.8 输出图形 2

/*        L   *
  *       1   1
  **      2   2
  ***     3   3
  ****    4   4
  *****   5   5
*/

public class TestStarTriangle {

    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();
        }
    }
}

2.8 输出图形 3

/*
                 L  _  *
      *          1  4  1
     ***         2  3  3
    *****        3  2  5
   ******* 		 4  1  7
  *********		 5  0  9
  
				_ = 总共行数 - L
				* = 2 * L - 1
*/

public class TestStarRegularTriangle {

    public static void main(String[] args) {

        // 1. 外层循环控制总行数
        for (int i = 1; i <= 5; i++) {

            // 2. 先处理空格,空格的总数是 总行数 - 当前行号
            for (int j = 1; j <= 5 - i; j++) {
                System.out.print(' ');
            }

            // 3. 处理星星,星星个数是 当前行号 * 2 - 1
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }

            System.out.println();
        }
    }
}

2.9 输出图形 4

/*
    *
   ***
  *****
 *******
*********
		   L  _  *
 *******    1  1  7
  *****     2  2  5
   ***      3  3  3
    *       4  4  1
    
    		_ = 总共行数 - L
			* = 2 * L - 1
*/

public class TestRhombus {

    public static void main(String[] args) {

        // 上半部分
        // 1. 外层循环控制总行数
        for (int i = 1; i <= 5; i++) {

            // 2. 先处理空格,空格的总数是 总行数 - 当前行号
            for (int j = 1; j <= 5 - i; j++) {
                System.out.print(' ');
            }

            // 3. 处理星星 星星个数是 当前行号 * 2 - 1
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print('*');
            }

            System.out.println();
        }

        // 下半部分
        // 1. 外层循环控制总行数,是上半部分行数-1
        for (int i = 1; i <= 5 - 1; i++) {

            //2. 先处理空格,空格的个数是当前行号
            for (int j = 1; j <= i; j++) {
                System.out.print(' ');
            }

            //3. 星星个数是中间行 - 当前行号 * 2
            for (int k = 1; k <= 5 * 2 - 1 - 2 * i; k++) {
                System.out.print('*');
            }

            System.out.println();
        }
    }
}