1.1.4 分支, if, if else, if elseif else, switch,循环,for,break,continue,双重for,while, do while

&&&&&总结&&&&&

1, 分支结构

    if分支结构, if else分支结构, if elseif else分支结构, switch case分支结构

2, 循环结构

    for循环, break和continue关键字, 双重for循环, while循环, do while循环

 

4  流程控制语句    

4.1  分支结构(重中之重)

4.1.1  分支结构的概念

    • 当需要进行条件判断并做出选择时,使用分支结构。

 

4.1.2  if分支结构

    • if(条件表达式) { 语句块; }

    • 判断条件表达式是否成立          => 若成立,则执行语句块;           => 若不成立,则跳过语句块;

 

代码:    编程使用if分支结构模拟网吧上网的过程

/*
	编程使用if分支结构模拟网吧上网的过程
*/
 
 import java.util.Scanner;
 
 public class IfTest {
	 
	 public static void main(String[] args) {
		 
		//1.提示输入年龄并存入变量
		System.out.println("请输入您的年龄:");
		Scanner sc = new Scanner(System.in);
		int age = sc.nextInt();
		//2.判断是否成年并给出提示
		if (age >= 18) {
			System.out.println("开心的浏览起了网页...");
		}
		//3.打印一句话
		System.out.println("美好的时光总是短暂的");
	 }
 }

 

案例题目

    • 提示用户输入两个整数,使用if分支结构找到最大值并打印出来。

代码:  编程实现,提示用户输入两个整数,使用if分支结构找到最大值并打印出来

/*
	编程实现,提示用户输入两个整数,使用if分支结构找到最大值并打印出来
*/

import java.util.Scanner;

public class IfMax {
	
	public static void main(String[] args) {
		
		//1.提示用户输入,并存入两个变量
		System.out.println("请输入两个整数:");
		Scanner sc = new Scanner(System.in);
		int num1 = sc.nextInt();
		int num2 = sc.nextInt();
		//2.查找最大值并打印
		/*if(num1 >= num2) {
			System.out.println("最大值为:" + num1);
		}
		if(num2 > num1) {
			System.out.println("最大值为:" + num2);
		}
		*/
		
		//方式二:假设第一个最大并记录
		int max = num1;
		
		if(num2 >= max) {
			max = num2;
		}
		System.out.println("最大值为:" + max);
	}
}

 

4.1.3  if else分支结构

    • if(条件表达式) { 语句块1; } else { 语句块2; }

    • 判断条件表达式是否成立

        => 若成立,则执行语句块1;         => 若不成立,则执行语句块2;

代码:    编程使用if else分支结构来模拟考试成绩查询过程

/*
	编程使用if else分支结构来模拟考试成绩查询过程
*/

import java.util.Scanner;

public class IfElse {
	public static void main(String[] args) {
		
		//1.提示用户输入并记入变量
		System.out.println("请输入您的考试成绩:");
		Scanner sc = new Scanner(System.in);
		int score = sc.nextInt();
		
		//2.判断是否合格并给出提示
		if(score >= 60) {
			System.out.println("恭喜你考试通过了");
		} else {
			System.out.println("下学期来补考吧");
		}
		//3.打印一句话
		System.out.println("世界上最遥远的距离不是生与死,而是你在if我在else,似乎一直相伴却又永远分离 ");
	}
}

 

 

案例题目

    • 提示用户输入一个整数,使用if else分支结构判断该整数是负数还是非负 数并打印。

    • 使用if else分支结构判断该整数是正数、负数还是零。

代码:  编程实现,提示输入一个整数,使用if else判断正负并输出

/*
	编程实现,提示输入一个整数,使用if else判断正负并输出
*/

import java.util.Scanner;

public class IfMinus {
	
	public static void main(String[] args) {
		
		//1.提示输入整数存入变量
		System.out.println("请输入一个整数:");
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		
		//2.判断正负并输出
		/*if(num < 0) {
			System.out.println(num + "是一个负数");
		} else {
			System.out.println(num + "是一个非负数");
		}
		*/
		
		//3.判断是正是负还是0
		if(num < 0) {
			System.out.println(num + "是一个负数");
		} else {
			if(0 == num) {
				System.out.println(num + "是零");
			} else {
				System.out.println(num + "是一个正数");
			}
		}
		
		/*if(num < 0) {
			System.out.println(num + "是一个负数");
		} else if (0 == num) { 
			System.out.println(num + "是零");
		} else {
			System.out.println(num + "是一个正数");
		}
		*/
	}
}

 

 

4.1.4  if else if else分支结构

    • if(条件表达式1) {

             语句块1;

      } else if(条件表达式2) {

             语句块2;

     } else {

             语句块n;

     }

• 判断条件表达式1是否成立

    => 若成立,则执行语句块1;          => 若不成立,则判断条件表达式2是否成立

    => 若成立,则执行语句块2;          => 若不成立,则执行语句块n;

代码:    编程实现 if  elseif  else分支结构的使用,模拟购票

/*
	编程实现 if    else if		else分支结构的使用,模拟购票
*/

import java.util.Scanner;

public class IfElseIfElse {
	
	public static void main(String[] args) {
		
		//1.提示输入身份信息并记入变量
		System.out.println("请输入您的身份信息:");
		Scanner sc = new Scanner(System.in);
		String str = sc.next();
		
		//判断身份信息
		if ("军人".equals(str)) {
			System.out.println("免费乘坐");
		} else if("学生".equals(str) ) {
			System.out.println("半价购票");
		} else {
			System.out.println("请购买全票");
		}
		
		//3.打印一句话
		System.out.println("坐上了火车去拉萨,去看那美丽的布达拉 ");
	}
}

 

案例题目

    • 根据用户输入的薪水计算个人所得税并打印出来,其中个税起征点为: 5000元,

    具体规则如下:

    

代码:  编程实现,输入薪水,使用if else if else计算个人所得税并打印

/*
	编程实现,输入薪水,计算个人所得税并打印 
*/

import java.util.Scanner;

public class Ifsalary {
	
	public static void main(String[] args) {
		
		//1.提示输入薪水并存入变量
		System.out.println("请输入本月薪水:");
		Scanner sc = new Scanner(System.in);
		//局部变量: 作用范围是声明开始,到方法体结束
		int salary = sc.nextInt();
		
		//2.计算所得税
		double gainrate = 0.0;
		if(salary <= 5000) {
			 gainrate = 0.0;	//块变量:控制结构内部的声明仅用于当前结构
		} else if(salary > 5000 && salary <= 8000) {
			//gainrate = (salary - 5000) * 0.03;  
			gainrate = (salary - 5000) * 0.03 - 0;
		} else if(salary > 8000 && salary <= 17000) {
			//gainrate = (salary - 8000) * 0.1 + 90;
			gainrate = (salary - 5000) * 0.1 - 210;
		} else if(salary > 17000 && salary <= 30000) {
			gainrate = (salary - 5000) * 0.2 - 1410;
			//gainrate = (salary - 17000) * 0.2 + 990;
		} else if(salary > 30000 && salary <= 40000) {
			gainrate = (salary - 5000) * 0.25 - 2660;
			//gainrate = (salary - 30000) * 0.25 + 3590;
		} else if(salary > 40000 && salary <= 60000) {
			gainrate = (salary - 5000) * 0.3 - 4410;
			//gainrate = (salary - 40000) * 0.3 + 6090;
		} else if(salary > 60000 && salary <= 85000) {
			gainrate = (salary - 5000) * 0.35 - 7160;
			//gainrate = (salary - 60000) * 0.35 + 12090;
		} else {
			gainrate = (salary - 5000) * 0.45 - 15160;
			//gainrate = (salary - 85000) * 0.45 + 20840;
		}
		
		//3.打印所得税
		System.out.println("本月纳税额为:" + gainrate);
	}
}

 

 

案例题目

    • 出租车计费方式:由里程钱数和等候时间钱数相加得出。

    • 里程数前3公里13元,超过3公里到15公里部分每公里2元,15公里以上部 分每公里3元。

    • 等候时间每2分半1元,不足部分不要钱。

    • 输入公里数和等候秒数,输出车费。

    • 16公里,等候290秒,车费 = 13 +(15-3)*2 + (16-15)*3 + 1 = 41

代码:  编程实现,出租车计费系统 ,  if else if else

/*
	编程实现,出租车计费系统
*/

import java.util.Scanner;

public class TaxiPrice {
	
	public static void main(String[] args) {
		
		//1.提示输入公里数和等候秒数存入变量
		System.out.println("请输入公里数和等候秒数:");
		Scanner sc = new Scanner(System.in);
		int km = sc.nextInt();
		int sec = sc.nextInt();
		int kmprice,secprice;
		
		//2.计算费用
		if(km <= 3) {
			kmprice = 13; 
		} else if(km > 3 && km <= 15) {	//这里可以写成  else(km <= 15),不加前面的限制也可
			kmprice = (km - 3) * 2 + 13;
		} else {
			kmprice = (km - 15) *3 + 24 + 13;
		}
		secprice = sec / 150;
		
		//3.打印车费
		System.out.println(km + "公里且等候时间" + sec + "秒,总计车费为:" + (secprice + kmprice));
	}
}

 

案例题目

    • 提示用户输入考试的成绩,使用if-else if-else分支结构判断所在等级并打印。

    [90 ~ 100] 等级A

      [80 ~ 89] 等级B

      [70 ~ 79] 等级C

      [60 ~ 69] 等级D

        [0 ~ 59] 等级E

代码:  使用if-else if-else 编程实现等级判断

/*
	编程实现等级判断
*/

import java.util.Scanner;

public class LvJudge {
	
	public static void main(String[] args) {
		
		//1.提示输入考试成绩
		System.out.println("请输入考试成绩:");
		Scanner sc = new Scanner(System.in);
		int score = sc.nextInt();
		char Lv = 'F';
		
		//2.判断等级并打印
		if(score < 60) {			//小于60的设置为default
			Lv = 'E';
		} else if(score < 70) {		//61到69对10去商,结果都是6
			Lv = 'D';
		} else if(score < 80) {
			Lv = 'C';
		} else if(score < 90) {
			Lv = 'B';
		} else if(score <= 100) {
			Lv = 'A';
		}
		System.out.println("您所在的等级为:" + Lv);
	}
}

 

4.1.5  switch case分支结构

    • switch(变量/表达式) {

            case 字面值1: 语句块1; break;

            case 字面值2: 语句块2; break;

            ...

            default:语句块n;

      }

 

    • 计算变量/表达式的数值

        => 判断是否匹配字面值1                            => 若匹配,则执行语句块1         => 执行break跳出当前结构

        => 若不匹配,则判断是否匹配字面值2      => 若匹配,则执行语句块2         => 执行break跳出当前结构

        => 若不匹配,则执行语句块n

 

    • switch()中支持的数据类型有:

        byte、short、char以及int类型,从jdk1.5 开始支持枚举类型,从jdk1.7开始支持String类型。

 

代码;   编程实现,使用switch语句判断等级

/*
	编程实现,使用switch语句判断等级
*/

import java.util.Scanner;

public class SwitchLvJudge {
	
	public static void main(String[] args) {
		
		//1.提示输入考试成绩
		System.out.println("请输入考试成绩:");
		Scanner sc = new Scanner(System.in);
		int score = sc.nextInt();
		char Lv = 'F';
		
		//2.使用switch判断并打印
		switch(score / 10) {
			case 10://Lv = 'A';
			case 9: Lv = 'A';break;		//case穿透
			case 8: Lv = 'B';break;
			case 7: Lv = 'C';break;
			case 6: Lv = 'D';break;
			default: Lv = 'E';
		}
		System.out.println("您所在的等级为:" + Lv);
		
		//3.打印一句话
		System.out.println("-----------------------------------------------------------------------");
		System.out.println("世界上最痴情的等待,就是我当case你当switch,或许永远都不会选到自己!");
	}
}

 

案例题目

    • 使用switch case分支结构模拟以下菜单效果。

    

代码:  编程实现,switch 实现字符界面

/*
	编程实现,switch 实现字符界面
*/

import java.util.Scanner;

public class SwitchMenu {
	
	public static void main(String[] args) {
		
		//1.绘制字符界面
		System.out.println(" ");
		System.out.println("         欢迎来到拉勾教育");
		System.out.println("-------------------------------------");
		System.out.print(" [1]学员系统");		// println里面的ln相当于换行的作用
		System.out.println("    [2]管理员系统");
		System.out.println(" [0]退出系统");
		System.out.println("-------------------------------------");
		System.out.println("请选择要进入的系统:");
		Scanner sc = new Scanner(System.in);
		int choose = sc.nextInt();

		//2.使用switch模拟用户的选择并给出提示
		switch(choose){
			case 1: System.out.println("正在进入 [1]学员系统 ..."); break;
			case 2: System.out.println("正在进入 [2]管理员系统 ..."); break;
			case 0: System.out.println("谢谢使用,下次再见!"); break;
			default:System.out.println("输入有误,请重新输入");
		}
	}
}

 

4.2  循环结构(重中之重)

4.2.1  循环结构的概念

    • 在Java程序中若希望重复执行一段代码时,就需要使用循环结构。

    • 任何复杂的程序逻辑都可以通过顺序、分支、循环三种程序结构实现。

 

4.2.2  for循环

    • for(初始化表达式; 条件表达式; 修改初始值表达式) {

            循环体;

      }

    • 执行初始化表达式

        => 判断条件表达式是否成立            => 成立则执行循环体             => 修改初始值表达式

        => 判断条件是否成立                      => 若不成立,则循环结束

 

代码:  编程实现for循环的使用,模拟玩游戏的过程

/*
	编程实现for循环的使用,模拟玩游戏的过程
*/

public class ForTest {
	
	public static void main(String[] args) throws Exception {
		
		for(int i = 1; i <= 10; i++) {	
			System.out.println("今晚吃鸡,大吉大利,正在进行第" + i + "场游戏...");
			Thread.sleep(5000);	//表示模拟睡眠5秒的效果
			System.out.println("本场游戏结束!\n\n\n");
		}
		
		System.out.println("该休息了,否则明天就要迟到了");
	}
}

 

案例题目

    • 使用for循环打印1-100的所有奇数,使用三种方式。

代码:   编程实现,打印1-100的所有奇数,  三种方式

/*
	编程实现,打印1-100的所有奇数
*/
public class ForNum {
	
	public static void main(String[] args) {
		
		//方式一:根据奇数概念打印
		int count = 0;
		for(int i = 1; i < 101; i++) {
			if((i % 2) != 0) {
				System.out.print(i + " ");
				count++;
				if(10 == count) {
					System.out.println("");
					count = 0;
				}
			}
		}
		
		System.out.println("------------------------------------");
		//方式二:根据等差数列打印
		for(int i = 1; i <= 100; i += 2) {
			System.out.print(i + " ");
			count++;
			if(10 == count) {
				System.out.println("");
				count = 0;
			}
		}
		
		System.out.println("------------------------------------");
		//方式三:
		for(int i = 1; i <= 50; i++) {
			System.out.print(i * 2 - 1 + " ");
			count++;
			if(10 == count) {
				System.out.println("");
				count = 0;
			}
		}
	}
}

 

案例题目

    • 使用for循环实现累加:1+2+...+10000=?最后打印出来。

代码:  编程实现,1到10000的累加并打印

/*
	编程实现,1到10000的累加并打印
*/
public class ForSum {
	
	public static void main(String[] args) {
		
		int sum = 0;
		for(int i = 1; i <= 10000; i++) {
			sum += i;
		}
		System.out.println("1到10000的和为:" + sum);
		
	}
}

 

 

案例题目

    • 使用for循环打印三位数中所有水仙花数。

    • 所谓“水仙花数”即一个整数满足其值等于各个数位的立方和。

    • 如:153是一个水仙花数,因为153=1^3+5^3+3^3。

代码:  编程,打印三位数中所有水仙花数

/*
	编程,打印三位数中所有水仙花数
*/
public class ForFlower {
	
	public static void main(String[] args) {
		
		int count = 0;
		System.out.println("三位数中所有水仙花数是:" );
		for(int i = 100; i <= 999; i++) {
			int i1 = i / 100;
			int i2 = (i % 100) / 10;
			int i3 = i % 10;
			if(i == i1 * i1 * i1 + i2 * i2 * i2 + i3 * i3 * i3) {
				System.out.print(" " + i);
				count++;
				if(5 == count) {
					System.out.println("");
					count = 0;
				}
			}
		}	
	}
}

 

 

4.2.3  continue关键字

    • continue语句用在循环体中,用于结束本次循环而开始下一次循环。

 

案例题目

    • 使用for循环打印1 ~ 20之间的所有整数,若遇到5的倍数则跳过不打印。

代码:  编程实现,使用for打印1~20之间所有整数,遇到5的倍数则跳过不打印

/*
	编程实现,使用for打印1~20之间所有整数,遇到5的倍数则跳过不打印
*/
public class ForJump5 {
	
	public static void main(String[] args) {
		
		for(int i = 1; i <= 20; i++) {
			if(0 == i % 5) {
				continue;
			}
			System.out.println("i = " + i);
		}
	}
}

 

4.2.4  break关键字

    • break用于退出当前语句块,break用在循环体中用于退出循环。

    • for(;;)

        - 这种没有循环条件的循环叫做 无限循环,俗称“死循环” 。

 

案例题目

    • 不断地提示用户输入聊天内容并输出,直到用户输入”bye”结束聊天。

代码:  不断提示用户输入新内容,bye退出

/*
	不断提示用户输入新内容,bye退出
*/

import java.util.Scanner;

public class ForBye {
	
	public static void main(String[] args) {
		
		/*
		System.out.println("请输入新内容:");
		Scanner sc = new Scanner(System.in);
		String str = sc.next();
		System.out.println("您输入的是:" + str);
		
		for( ; !("bye".equals(str)); ) {
			System.out.println("请输入新内容:");
			str = sc.next();
			System.out.println("您输入的是:" + str);
		}
		*/ 
		
		//5.声明一个boolean类型变量作为发送方标志
		boolean flag = true;
		
		//4.使用无限循环来模拟不断地聊天
		for(;;) {
			//1.提示用户输入要发送的聊天内容并使用变量记录
			System.out.println("请" + (flag? "张三" : "李四") + "输入新内容:");
			Scanner sc = new Scanner(System.in);
			String str = sc.next();
			
			//2.判断是否是bye,是则结束聊天
			if("bye".equals(str)) {
				System.out.println("已退出,谢谢使用!");
				break;
			}
			//3.不是则打印输入的内容
			//System.out.println((flag? "聊天内容是:") + str);
			System.out.println((flag? "张三说:" : "李四说:") + str + "\n\n\n");
			flag = !flag;
		}
	}
}

 

案例题目

    • 猜数字游戏

    • 随机生成数字n(1-100), 等待用户输入猜测数据, 根据用户的输入比较输出 猜大了,猜小了,猜对了,

        如果用户猜对了就结束游戏 。

代码:     编程使用for循环实现猜数字游戏

/*
	编程使用for循环实现猜数字游戏
*/

import java.util.Random;
import java.util.Scanner;

public class ForGuess {
	
	public static void main(String[] args) {
		
		//1.生成1~100之间的随机数并用变量记录
		Random ra = new Random();
		int temp = ra.nextInt(100) + 1;
		//System.out.println("temp = " + temp);

		//4.声明一个int变量来统计用户猜测的次数
		int count = 0;
	
		//2.提示输入1~100之间猜测的整数并使用变量记录
		System.out.println("\n请输入一个猜测数(1~100之间):");
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
	
		//3.使用用户输入的整数与随机数之间比较大小,并给出对应的提示
		for(;;) {
			if(num > temp) {
				System.out.println("太...太大了,再试一次吧!\n");
				num = sc.nextInt();
				count++;
			} else if(num < temp) {
				System.out.println("太...太小了,再试一次吧!\n");
				num = sc.nextInt();
				count++;
			} else {
				count++;
				System.out.println("恭喜,大小刚刚好!您一共尝试了" + count +"次\n\n");
				break;
			}
		}
		
		if(1 == count) {
			System.out.println("你果然棒棒");
		} else if(count <= 6) {
			System.out.println("666,继续加油!");
		} else {
			System.out.println("菜鸡,多来几次吧");
		}
	}
}

 

4.2.5  双重for循环 

    双重for循环的格式

    • for(初始化表达式1; 条件表达式2; 修改初始值表达式3) {

                for(初始化表达式4; 条件表达式5; 修改初始值表达式6) {

                        循环体;

                }

       }

 

    双重for循环的执行流程

    • 执行表达式1

    => 判断表达式2是否成立                    => 若成立,则执行表达式4           => 判断表达式5是否成立

    => 若成立,则执行循环体                  => 执行表达式6                             => 表达式5是否成立

    => 若不成立,则内层循环结束           => 表达式3                                    => 表达式2是否成立

    => 若不成立,则外层循环结束

 

   双重for循环的特点

       • 外层循环用于控制打印的行数,内层循环用于控制打印的列数,外层循 环改一下,内层循环从头到尾跑一圈。

       • 在以后的开发中若需要打印多行多列时,需要使用双重循环。

       • 多重循环不宜嵌套太多层,否则效率很低。一般到三重循环即可,最常 见的就是双重循环。

 

代码:   编程实现双重for循环的使用

/*
	编程实现双重for循环的使用
*/
public class ForFor {
	
	public static void main(String[] args) {
		
		for (int i = 1; i <= 5; i++) {
			for(int j = 1; j <=5; j++) {
				System.out.print("厉害了我的哥  ");
			}
			System.out.println("");	
		}	
	}
}

 

 

案例题目

    • 使用双重for循环分别打印以下图案

    

代码:    编程使用双重for打印星星

/*
	编程使用双重for打印星星
*/
public class ForForStar {
	
	public static void main(String[] args) {
		
		//1.打印第1个星星图
		System.out.println();
		for(int i = 1; i <= 5; i++) {
			for(int j = 1; j <= 5; j++) {
				System.out.print("*");
			}
			System.out.println();
		
		}
		System.out.println();
		
		//2.打印第2个星星图
		System.out.println("-------------------------------------");
		System.out.println();
		for(int i = 1; i <= 5; i++) {
			for(int j = 1; j <= i; j++) {
				System.out.print("*");
			}
			System.out.println();
			
			
		}
		System.out.println();
		
		//3.打印第3个星星图
		System.out.println("-------------------------------------");
		System.out.println();
		for(int i = 1; i <= 5; i++) {
			for(int j = 1; j <= 6 - i; j++) {
				System.out.print("*");
			}
			System.out.println();
			
			
		}
		System.out.println();
		
		//4.打印第4个星星图
		System.out.println("-------------------------------------");
		System.out.println();
		for(int i = 1; i <= 5; i++) {
			for(int j = 1; j <= 5 - i; j++) {
				System.out.print(" ");
			}
			for(int k = 1; k <= 2 * i - 1; k++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

 

案例题目

    • 使用双重for循环打印九九乘法表。

    

代码:    使用双重for打印99乘法表

/*
	使用双重for打印99乘法表
*/
public class ForFor99 {
	
	public static void main(String[] args) {
	
	System.out.println("---------------------------------------");
	System.out.println();
	//1.使用外层for控制打印的行数,一共9行
	outer: for(int i = 1; i <= 9; i++) {
		//2.用内层for控制打印的列数,最多9列,规律是与当前行数相等
		for(int j = 1; j <= i; j++) {
			//3.拼接结果
			System.out.print(i + "*" + j + "=" + (i * j) + "  " );
			//4.打印完6*6 = 36后结束整个打印 
			if(6 == j) {
				//break;	//主要用于跳出循环,但该关键字只能跳出当前所在循环
				break outer;	//表示可以跳出所标循环
			}
		}
		System.out.println();
		
		/*if(6 == i) {
			break;
		}*/
	}
	
	System.out.println();
	System.out.println("--------------------------------------");
	System.out.println();
	for(int i = 1; i <= 9; i++) {
		for(int j = 1; j <= 10 - i; j++) {
			System.out.print(i + "*" + j + "=" + (i * j) + "  " );
		}
		System.out.println();
	}

		
	System.out.println("-------------------------------------");
	System.out.println();	
	for(int i = 1; i <= 9; i++) {
		for(int k = 1; k <= 9 - i; k++){
			System.out.print("        ");
		}
		for(int j = 1; j <= i; j++) {
			System.out.print(i + "*" + j + "=" + (i * j) + "  " );
		}
		System.out.println();
	}
	
	
	System.out.println("-------------------------------------");
	System.out.println();
	for(int i = 1; i <= 9; i++) {
		for(int k = 1; k <= i - 1; k++){
			System.out.print("        ");
		}
		for(int j = i; j <= 9; j++) {
			System.out.print(i + "*" + j + "=" + (i * j) + "  " );
		}
		System.out.println();
	}
}

 

 

break关键字跳出多层循环

    • 在嵌套的循环结构中,break用于退出所在循环体。

    • 如果要退出外层循环体,需要使用标号的方式。

    for (...) {                                outer: for (...) {

              for(...) {                                           for(...) {

                       break;                                             break outer;

              }                                                      }

    }                                                       }

 

案例题目

    • 使用双重for循环打印2~100之间的所有素数。

    • 当一个数只能被1和它本身整除时,这个数就叫做素数或质数。

代码:    打印2~100之间所有的素数

/*
	打印2~100之间所有的素数
*/
public class ForForPrime {
	
	public static void main(String[] args) {
		
		for(int i = 2; i <= 100; i++) {
			boolean flag = true;
			//针对每一个当前的整数都要判断是否是素数
			//判断方法为:2到 它本身-1之间的所有整数都无法整除,则为素数
			for(int j = 2; j <= Math.sqrt(i); j++) {
			//只需要判断2到该数的平方根即可
			//for(int j = 2; j <= i - 1; j++) {
				if(0 == i % j) {
					flag = false;
					//System.out.println(i + "不是素数");
					break;
				}
			}
			if(flag) {
				System.out.println(i + "是素数");
			}
		}
			
		System.out.println("--------------------------------------");
	}
}

 

4.2.6  while循环

    • while(条件表达式) {

            循环体;

       }

• 判断条件表达式是否成立                             => 若成立,则执行循环体

        => 判断条件表达式是否成立                  => 若不成立,则循环结束

 

案例题目

    • 使用while循环计算调和数列的和并打印,即: 1/1 + 1/2 + ... + 1/n。

代码:    编程实现调和数列的累加

/*
	编程实现调和数列的累加
*/

import java.util.Scanner;

public class While {
	public static void main(String[] args) {
		
		System.out.println("请输入想要计算的项数n:");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		double sum = 0.0;
		int i = 1;
		
		while(i <= n) {
			sum += (1.0 / i);
			i++;
		}
		
		System.out.println("前"+ n + "项的和为:" + sum);
	}
}

 

 

   while循环和for循环比较

    • while循环和for循环完全可以互换,当然推荐使用for循环。

    • while循环更适合于明确循环条件但不明确循环次数的场合中。

    • for循环更适合于明确循环次数或范围的场合中。

    • while(true) 等价于 for(;;) 都表示无限循环。

 

案例题目

    • 提示用户输入一个任意位数的正整数然后反向输出。

代码:     编程实现,输入一个任意位数的正整数然后反向输出,while

/*
	编程实现,提示用户输入一个任意位数的正整数然后反向输出
*/

import java.util.Scanner;

public class ReverNum {
	
	public static void main(String[] args) {
		
		/*
		System.out.println("请输入任意正整数");
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		int sum = 0;
		int N1;
		
		while(num % 10 != 0) {
			N1 = num % 10;
			num = num / 10;
			sum = sum * 10 + N1;
		}
		
		System.out.println("反向输出的结果为:" + sum);
		*/
		System.out.println("请输入任意正整数");
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		
		while(num > 0) {
			System.out.print(num % 10);	//拆分个位数
			num /= 10;	//丢弃个位数
		}
	}
}

 

4.2.7  do while循环(熟悉)

    • do {

               循环体;

      } while(条件表达式);  

    • 执行循环体 => 判断条件表达式是否成立                  => 若成立,则执行循环体

         => 判断条件表达式是否成立                                  => 若不成立,则循环结束

    • do-while循环主要用于至少执行一次循环体的场合中。

 

案例题目

    • 使用do while循环来模拟学习任务是否合格的检查, 如果合格则停止, 否则就重新完成学习任务。

代码:    编程使用dowhile来模拟学习效果的检查

/*
	编程使用dowhile来模拟学习效果的检查
*/

import java.util.Scanner;

public class DoWhileCheck {
	
	public static void main(String[] args) throws Exception{
		
		String msg = null;
		do {
			System.out.println("正在疯狂学习中...");
			Thread.sleep(5000);
			System.out.println("是否合格?(y/n)");
			Scanner sc = new Scanner(System.in);
			msg = sc.next();
		} while(!"y".equals(msg));
		
		System.out.println("恭喜任务合格!");
		
		System.out.println("---------------------------------------");
		
		//典故:十动然拒
		int = 1;
		while(i <= 10000) /* ; */ {
			System.out.println("I love You !");
		}
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值