一、随堂复习
1.1(了解)流程控制结构
- 顺序结构
- 分支结构
- if-else
- switch-case
- 循环结构
- for
- while
- do-while
1.2分支结构之1:if-else
- 在程序中,凡是遇到了需要使用分支结构的地方,都可以考虑使用if-else。
- if-else嵌套的练习多关注
基本语法:
分支结构1:if-else条件判断结构
1.格式
格式1:
if(条件表达式){
语句块;
}
格式2:
if(条件表达式){
语句块1;
}else{
语句块2;
}
格式3:"多选一"
if(条件表达式1){
语句块1;
}else if (条件表达式2){
语句块2;
}...
}else if (条件表达式n){
语句块n;
}else{
语句块n+1;
}
class IfElseTest{
public static void main(String[] args) {
/*
案例1:成年人心率的正常范围是每分钟60-100次。体检时,
如果心率不在此范围内,则提示需要做进一步的体检。
*/
int heartBeats = 61;
//错误写法
//if (60 <= heartbeats <= 100)
//因为int型和boolean型不能做比较
if (heartBeats < 60 || heartBeats > 100){
System.out.println("您需要做进一步的检查");
}else{
System.out.println("您的心率正常");
}
System.out.println("体检结束");
//**********************************
/*
案例2:定义一个整数,判断是偶数还是奇数
*/
int num1 = 13;
if (num1 % 2 == 0)
{
System.out.println(num1 + "是偶数");
}else{
System.out.println(num1 + "是奇数");
}
}
}
案例:
练习1:
岳小鹏参加Java考试,他和父亲岳不群达成承诺:
如果:
成绩为100分时,奖励一辆跑车;
成绩为(80,99]时,奖励一辆山地自行车;
当成绩为[60,80]时,奖励环影城一日游;
其他时,胖揍一顿。
说明:默认成绩是在[0,100]范围内
结论:
1.如果多个条件表达式之间没有交集(理解是互斥关系),则哪个条件表达式声明在上面,哪个声明在下面都可以。
如果多个条件表达式之间是包含关系,则需要将范围小的条件表达式声明在范围大的条件表达式的上面。
否则,范围小的条件表达式不可能被执行。
class IfElseTest1{
public static void main(String[] args){
int score = 61;
/*
if (score == 100)
{
System.out.println("奖励一辆跑车");
}else if(score > 80 && score <= 99){
System.out.println("奖励一辆山地自行车");
}else if(score >= 60 && score <= 80){
System.out.println("奖励环影城一日游");
}else{
System.out.println("奖励胖揍一顿");
}
*/
//*****************************
if (score == 100)
{
System.out.println("奖励一辆跑车");
}else if(score > 80){
System.out.println("奖励一辆山地自行车");
}else if(score >= 60){
System.out.println("奖励环影城一日游");
}else{
System.out.println("奖励胖揍一顿");
}
//特别的,不用else也可以
if (score == 100)
{
System.out.println("奖励一辆跑车");
}else if(score > 80){
System.out.println("奖励一辆山地自行车");
}else if(score >= 60){
System.out.println("奖励环影城一日游");
}
/*else{
System.out.println("奖励胖揍一顿");
}
*/
}
}
练习2:
测试if-else的嵌套使用
案例:
由键盘输入三个整数分别存入变量num1、num2、num3,对它们进行排序(使用 if-else if-else),并且从小到大输出。
扩展:你能实现从大到小顺序的排序吗?
1.从开发经验上讲,没有写过超过三层的嵌套if-else结构。
2.如果if-else中的执行语句块中只有一行执行语句,则此执行语句所在的一对{}可以省略。但是,不建议省略。注:看练习1。
class IfElseTest2{
public static void main(String[] args){
int num1 = 23;
int num2 = 43;
int num3 = 39;
//int num1 =23, int num2 = 43, int num3 = 39;
//两种定义方式
if (num1 > num2){
if (num3 >= num1){
System.out.println(num2 + "," + num1 + "," + num3);
System.out.println("扩展");
System.out.println(num3 + "," + num1 + "," + num1);
}else if (num3 <= num2){
System.out.println(num3 + "," + num2 + "," + num1);
System.out.println("扩展");
System.out.println(num1 + "," + num2 + "," + num2);
}else{
System.out.println(num2 + "," + num3 + "," + num1);
System.out.println("扩展");
System.out.println(num2 + "," + num3 + "," + num1);
}
}else{
if (num3 >= num2){
System.out.println(num1 + "," + num2 + "," + num3);
System.out.println("扩展");
System.out.println(num3 + "," + num2 + "," + num1);
}else if (num3 <= num1){
System.out.println(num3 + "," + num1 + "," + num2);
System.out.println("扩展");
System.out.println(num2 + "," + num1 + "," + num3);
}else{
System.out.println(num1 + "," + num3 + "," + num2);
System.out.println("扩展");
System.out.println(num2 + "," + num3 + "," + num1);
}
}
//练习1:对下列代码,若有输出,指出输出结果。
int x = 4, y = 1;
if (x > 2){
if (y > 2)
System.out.println(x + y);
System.out.println("我爱学习");//输出结果为:我爱学习,因为如果if-else中的执行语句块中只有一行执行语句,则此执行语句所在的一对{}可以省略。
}else
System.out.println("x is " + x);
//练习2:
boolean b = true;
//如果写成if(b = false)能编译通过吗?如果能,结果是?
if (b == false) //建议写成if (!b)
{
System.out.println("b");
}else if (b){
System.out.println("a");
}else if (!b){
System.out.println("c");
}else{
System.out.println("d");
}
//输出结果为:a
/*
如果写成if(b = false)能编译通过
输出结果为:c
*/
//练习3:定义两个整数,分别为small和big,如果第一个整数small大于第二个整数big,就交换。输出显示small和big变量的值。
int small = 10;
int big = 9;
if (small > big){
System.out.println("small = " + small + ",big = " + big);
System.out.println("交换后");
int temp;
temp = big;
big = small;
small = temp;
System.out.println("small = " + small + ",big = " + big);
}else{
System.out.println("small = " + small + ",big = " + big);
}
/*
练习4:小明参加期末Java考试,通过考试成绩,判断其Java等级,成绩范围[0,100]
90 - 100 优秀
80 - 89 好
70 - 79 良
60 - 69 及格
60以下 不及格
*/
//写法一:把区间定死
System.out.println("小明的期末Java成绩是:[0-100]");
int score = 89;
if (score > 100 || score < 0){
System.out.println("你的Java成绩是错误的");
}else if (score >= 90 && score <= 100){
System.out.println("你的Java成绩属于优秀");
}else if (score >= 80 && score <= 89){
System.out.println("你的Java成绩属于好");
}else if (score >= 70 && score <= 79){
System.out.println("你的Java成绩属于良");
}else if (score >= 60 && score <= 69){
System.out.println("你的Java成绩属于及格");
}else{
System.out.println("你的Java成绩属于不及格");
}
//写法二:小范围放最上面
System.out.println("小明的期末Java成绩是:[0-100]");
int score1 = 89;
if (score1 > 100 || score1 < 0){
System.out.println("你的Java成绩是错误的");
}else if (score1 >= 90){
System.out.println("你的Java成绩属于优秀");
}else if (score1 >= 80){
System.out.println("你的Java成绩属于好");
}else if (score1 >= 70){
System.out.println("你的Java成绩属于良");
}else if (score1 >= 60){
System.out.println("你的Java成绩属于及格");
}else{
System.out.println("你的Java成绩属于不及格");
}
/*
练习5:编写程序,声明2个int型变量并赋值。判断两数之和,如果大于等于50,打印"hello world!"
*/
int num4 = 23, num5 = 43;
int temp = num4 + num5;
if (temp >= 50){
System.out.println("hello world!");
}
/*
练习6:编写程序,声明2个double型变量并赋值。判断第一个数大于10.0,且第2个数小于20.0,打印两数之和。否则,打印两数的乘积。
*/
double d1 = 13.4, d2 = 12.3;
if (d1 > 10.0 && d2 < 20.0){
System.out.println("两数之和为:" + (d1 + d2));
}else{
System.out.println("两数之积为:" + (d1 * d2));
}
/*
练习7:编写程序:
如果大于95℃,则打印“开水”
如果大于75℃,小于95℃,则打印“热水”
如果大于40℃,小于75℃,则打印“温水”
如果小于等于40℃,则打印“凉水”
*/
int waterTemper = 74;
if (waterTemper > 100 || waterTemper < 0){
System.out.println("水温不对");
}else if (waterTemper > 95){
System.out.println("此时水为开水");
}else if (waterTemper > 75){
System.out.println("此时水为热水");
}else if (waterTemper > 40){
System.out.println("此时水为温水");
}else{
System.out.println("此时水为凉水");
}
}
}
1.3分支结构之2:switch-case
- 在特殊的场景下,分支结构可以考虑使用switch-case
- 指定的数据类型: byte \ short \ char \ int;枚举类(jdk5.0) \ String (jdk7.0)。
- 可以考虑的常量值有限且取值情况不多。
- 特别之处: case穿透。(无break的地方)
- 在能使用switch-case的情况下,推荐使用switch-case,因为比if-else效率稍高
基本语法:
1.语法格式
switch(表达式){
case 常量1:
//执行语句1:
//beark;
case 常量2:
//执行语句2:
//break;
...
default:
//执行语句n:
//break;
2.执行过程:
根据表达式中的值,依次匹配case语句。一旦与某一个case中的常量相等,那么就执行此case中的执行语句。
执行完此执行语句之后,
情况1:遇到break,则执行break后,跳出当前的switch-case结构
情况2:没有遇到break,则继续执行其后的case中的执行语句。 ---> case 穿透
...
直到遇到break或者执行完所有的case及default中的语句,退出当前的switch-case结构
3.说明:
①swith中的表达式只能是特定的数据类型。如下:byte \ short \ char \ int \ 枚举(JDK5.0新增) \String(JDK7.0新增)
②case后都是跟的常量,使用表达式与这些常量做相等的判断,不能进行范围的判断。
③开发中,使用switch-case时,通常case匹配的情况都有限。
④break:可以使用在switch-case中。一旦执行此break关键字,就跳出当前的switch-case结构;
⑤default:类似于if-else中的else结构。
default是可选的,而且位置是灵活的。
4.switch-case 与 if-else之间的转换
①开发中凡是可以使用switch-case结构的场景,都可以改写为if-else。反之,不成立
②开发中,如果一个具体问题既可以使用switch-case,又可以使用if-else的时候,推荐使用switch-case。
为什么?switch-case相较于if-else效率较高。
③细节对比:
if-else语句优势
if语句的条件是一个布尔类型值,if条件表达式为true则进入分支,可以用于范围的判断,也可以用于等值的判断,使用范围更广。
switch语句的条件是一个常量值(byte \ short \ char \ int \ 枚举 \ String ),只能判断某个变量或表达式的结果是否等于某个常量值,使用场景较狭窄。
switch语句优势
当条件是判断某个变量或表达式是否等于某个固定的常量值时,使用if和switch都可以,习惯上使用switch更多。因为效率稍高。当条件是区间范围的判断时,只能使用if语句。
使用switch可以利用穿透性,同时执行对个分支,而if...else没有穿透性。
}
class SwitchCaseTest{
public static void main(String[] args) {
int num1 = 1;
switch (num1)
{
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("other");
break;
}
//另例
String season = "summer";
switch (season)
{
case "spring":
System.out.println("春天");
break;
case "summer":
System.out.println("夏天");
break;
case "autumn":
System.out.println("秋天");
break;
case "winner":
System.out.println("冬天");
break;
default:
System.out.println("季节输入有误");
break;
}
/*
//错误的例子:
int number = 20;
switch (number){
case number > 0:
System.out.println("正数");
break;
case number < 0:
System.out.println("正数");
break;
defaulf:
System.out.println("零");
break;
}
*/
}
}
案例:
练习1:
案例:使用switch-case实现:对学生成绩大于60分的,输出“合格”。低于60分的,输出“不合格”
class SwitchCaseTest1{
public static void main(String[] args){
//定义一个学生成绩的变量
int score = 78;
//方式1:
//根据需求,进行分支
/*
switch (score){
case 0:
System.out.println("不合格");
break;
case 1:
System.out.println("不合格");
break;
//...
case 100:
System.out.println("合格");
break;
default:
System.out.println("输入成绩有误");
break;
}
*/
//方式2;
switch (score / 10){
case 0:
System.out.println("不合格");
break;
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;
case 8:
System.out.println("合格");
break;
case 9:
System.out.println("合格");
break;
case 10:
System.out.println("合格");
break;
default:
System.out.println("输入成绩有误");
break;
}
//方式3:穿透
switch (score / 10){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("不合格");
break;
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println("合格");
break;
default:
System.out.println("输入成绩有误");
break;
}
//方式4:
switch (score / 60){
case 0:
System.out.println("不合格");
break;
case 1:
System.out.println("合格");
break;
default:
System.out.println("输入成绩有误");
break;
}
}
}
练习2:
案例:编写程序:从键盘上输入2023年的“month”和“day”,要求通过程序输出输入的日期为2023年的第几天。
import java.util.Scanner;
class SwitchCaseTest2{
public static void main(String[] args) {
//1.使用Scanner,从键盘获取2023年的month、day
Scanner input = new Scanner(System.in);
System.out.println("请输入2023年的月份:");
int month = input.nextInt();//阻塞式方法
System.out.println("请输入2023年的天:");
int day = input.nextInt();
//2.使用switch-case实现分支结构
int sumDays = 0;//记录总天数
//方式1:不推荐。存在数据的冗余
/*
switch (month)
{
case 0:
sumDays = day;
break;
case 1:
sumDays = 31 + day;
break;
//...
case 12:
sumDays = 31 + 28 + ... + 30 + day;
break;
}
*/
//方式2:利用递推的方法:
switch (month){
case 12:
sumDays += 30;
case 11:
sumDays += 31;
case 10:
sumDays += 30;
case 9:
sumDays += 31;
case 8:
sumDays += 31;
case 7:
sumDays += 30;
case 6:
sumDays += 31;
case 5:
sumDays += 30;
case 4:
sumDays += 31;
case 3:
sumDays += 28; //28:2月份的总天数
case 2:
sumDays += 31; //31:1月份的总天数
case 1:
sumDays += day;
break;
}
System.out.println("2023年" + month + "月" + day + "日" + "是当前的第" + sumDays + "天");
input.close();//为了防止内存泄露
}
}
练习3:
从键盘输入星期的整数值,输出星期的英文单词
import java.util.Scanner;
class SwitchCaseExer1{
public static void main(String[] args) {
//定义指定星期
Scanner input = new Scanner(System.in);
System.out.println("请输入星期值:");
int weekday = input.nextInt();
switch (weekday){
case 1:
System.out.println("星期" + weekday + "的英文是Monday");
break;
case 2:
System.out.println("星期" + weekday + "的英文是Tuesday");
break;
case 3:
System.out.println("星期" + weekday + "的英文是Wednesday");
break;
case 4:
System.out.println("星期" + weekday + "的英文是Thurday");
break;
case 5:
System.out.println("星期" + weekday + "的英文是Friday");
break;
case 6:
System.out.println("星期" + weekday + "的英文是Saturday");
break;
case 7:
System.out.println("星期" + weekday + "的英文是Sunday");
break;
default:
System.out.println("你的输入的星期有误");
}
input.close();
}
}
练习4:
使用switch把小写类型的char型转为大写。只转换a,b,c,d,e。其他的输出"other"
import java.util.Scanner;
class SwitchCaseExer2 {
public static void main(String[] args) {
System.out.println("请输入需要转换的字母:");
Scanner input = new Scanner(System.in);
char word = input.next().charAt(0);
switch (word){
case 'a':
System.out.println("字母" + word + "的大写是A");
break;
case 'b':
System.out.println("字母" + word + "的大写是B");
break;
case 'c':
System.out.println("字母" + word + "的大写是C");
break;
case 'd':
System.out.println("字母" + word + "的大写是D");
break;
case 'e':
System.out.println("字母" + word + "的大写是E");
break;
default:
System.out.println("你的输入有误!!");
break;
}
input.close();
}
}
练习5:
编写程序:从键盘上读入一个学生成绩,存放在变量score中,根据score的值输出其对应的成绩等级;
score >= 90 等级:A
70 <= score < 90 等级:B
60 <= score < 70 等级:C
score < 60 等级:D
import java.util.Scanner;
class SwitchCaseExer3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个学生的成绩[0,100]:");
int score = input.nextInt();
switch (score / 10){
case 0:
System.out.println("该学生的等级为D。");
break;
case 1:
System.out.println("该学生的等级为D。");
break;
case 2:
System.out.println("该学生的等级为D。");
break;
case 3:
System.out.println("该学生的等级为D。");
break;
case 4:
System.out.println("该学生的等级为D。");
break;
case 5:
System.out.println("该学生的等级为D。");
break;
case 6:
System.out.println("该学生的等级为C。");
break;
case 7:
System.out.println("该学生的等级为B。");
break;
case 8:
System.out.println("该学生的等级为B。");
break;
case 9:
System.out.println("该学生的等级为A。");
break;
case 10:
System.out.println("该学生的等级为A。");
break;
default:
System.out.println("该学生的成绩有误。");
break;
}
input.close();
}
}
练习6:
编写一个程序,为一个给定的年份找出其对应的中国生肖。中国的生肖基于12年一个周期,每年用一个动物代表:rat、ox、tiger、
rabbit、dragon、snake、horse、sheep、monkey、rooster、dog、pig。
提示:2022年:虎 2022 % 12 == 6
import java.util.Scanner;
class SwitchCaseExer4{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入年份:");
int year = input.nextInt();
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("你的输入有误!!");
}
input.close();
}
}
练习7:
随机产生3个1-6的整数,如果三个数相等,那么称为“豹子”,如果三个数之和大于9,称为“大”,如果三个数之和小于等于9,称为“小”,用户从键盘输入押的是“豹子”、“大”、“小”,并判断是否猜对了
提示:随机数 Math.random()产生[0,1)范围内的小数
如何获取[a,b]范围内的随机整数呢?(int)(Math.random() * (b - a + 1)) + a
import java.util.Scanner;
class SwitchCaseExer5 {
public static void main(String[] args) {
//随机产生三个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.println("请押宝(豹子、大、小)");
String ya = input.next();
//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 ? "猜中了" : "猜错了");
input.close();
}
}
练习8:
从键盘分别输入年、月、日,判断这一天是当年的第几天
注:判断一年是否是闰年的标准:
1)可以被4整除,但不可被100整除
2)可以被400整除
例如:1990,2200等能被4整除,但同时能被100整除,但不能被400整除,不是闰年
import java.util.Scanner;
class SwitchCaseExer6{
public static void main(String[] args){
//请输入年月日
Scanner input = new Scanner(System.in);
System.out.println("请输入年:");
int year = input.nextInt();
System.out.println("请输入月:");
int month = input.nextInt();
System.out.println("请输入日:");
int days = input.nextInt();
int day = 0;
//判断是否为闰年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
//通过月份来计算天数
switch (month)
{
case 12:
day += 30;
case 11:
day += 31;
case 10:
day += 30;
case 9:
day += 31;
case 8:
day += 31;
case 7:
day += 30;
case 6:
day += 31;
case 5:
day += 30;
case 4:
day += 31;
case 3:
day += 29;
case 2:
day += 31;
case 1:
day += days;
default:
System.out.println("您输入的月份有误!!");
}
}else{
switch (month)
{
case 12:
day += 30;
case 11:
day += 31;
case 10:
day += 30;
case 9:
day += 31;
case 8:
day += 31;
case 7:
day += 30;
case 6:
day += 31;
case 5:
day += 30;
case 4:
day += 31;
case 3:
day += 28;
case 2:
day += 31;
case 1:
day += days;
default:
System.out.println("您输入的月份有误!!");
}
}
System.out.println(year + "年" + month + "月" + days + "日,一共有天" + day + "天");
//关闭
input.close();
}
}
1.4循环结构之:for
基本语法:
循环结构一:for循环
1.java中规范了3中循环结构:for、while、do-while
2.凡是循环结构,就一定会有4个要素:
①初始化条件
②循环条件 --> 一定是boolean类型的变量或表达式
③循环体
④迭代部分
3.for循环的格式
for(①;②;④){
③
}
执行过程:① - ② - ③ - ④ - ② - ③ - ④ - ... - ②
//需求1:题目:输出5行Hello World!
class ForTest{
public static void main(String[] args){
//需求1:题目:输出5行Hello World!
/*
System.out.println("Hello World!");
System.out.println("Hello World!");
System.out.println("Hello World!");
System.out.println("Hello World!");
System.out.println("Hello World!");
*/
for (int i = 0; i <= 5 ; i++ ){//这里i的作用域为for内
System.out.println("Hello World!");
}
//此处编译不通过。因为i已经出了其作用域范围
//System.out.println(i);
//需求2:求出下面的程序的结果
int num1 = 1;
for (System.out.print("a"); num1 < 3 ; System.out.print("c"), num1++){//这里为,的原因是因为;降级为,
System.out.print("b");
}
//结果为:abcbc
System.out.println();//换行
//需求3:遍历1-100以内的偶数,并获取偶数的个数,获取所有的偶数的和
int count = 0;
int sum = 0;
for (int i = 1; i <= 100 ; i++){//这里i的作用域为for内
if ((i % 2) ==0){
System.out.println(i);
count +=1;
sum += i;
}
}
System.out.println("偶数的个数为:" + count);
System.out.println("偶数的总和为:" + sum);
}
}
案例:
练习1:
题目:输出所有的水仙花数,所谓水仙花是指一个3位数,其各个位上数字立方和等于其本身。
例如: 153 = 1*1*1 + 5*5*5 + 3*3*3
class ForTest1{
public static void main(String[] args) {
//遍历所有的3位数
for (int i = 100 ; i <= 999 ; i++ ){
//针对于每一个三位数i,获取其各个位上的数值
int ge = i % 10;
int shi = i / 10 % 10;
int bai = i / 100;
//判断是否满足水仙花数的规则
if (i == ge*ge*ge + shi*shi*shi + bai*bai*bai){
System.out.println(i + "是水仙花数");
}
}
}
}
练习2:
说明:输入两个正整数m和n,求其最大公约数和最小公倍数。
比如:12和20的最大公约数是4,最小公倍数是60。
约数:12为例,约数有1,2,3,4,6,12
20为例,约数有1,2,4,5,10,20
12和20之间的公约数为:1,2,4
所以最大公约数为4
说明:
1. 我们可以在循环结构中使用break。一旦执行break,就跳出(或结束)当前循环结构。
2.如何结束一个循环结构?
方式1:循环条件不满足。(既循环条件执行完以后是false)
方式2:在循环体中执行了break
class ForTest2{
public static void main(String[] args) {
int m = 12;
int n = 20;
//需求1:求最大公约数
//方式1:
int min = (m > n)? n : m;
int reture = 1;
for (int i = 1; i <= min ; i++ ){
if ((m % i == 0) && (n % i == 0)){
reture = i;
}
}
System.out.println("最大公约数为: " + reture);
//方式2:
for (int i = min; i >= 1 ; 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.5循环结构之2:while
基本语法:
循环结构之一:while循环
1.凡是循环结构,就一定会有4个要素:
① 初始化条件
② 循环条件 ---> 一定是boolean类型的变量或表达式
③ 循环体
④ 迭代部分
2.while的格式
①
while(②){
③
④
}
3.执行过程:① - ② - ③ - ④ - ② - ③ - ④ - ... - ②
4.for循环和while循环可以相互转换!
5.for循环和while循环的小区别:初始化条件的作用域范围不同。while循环中的初始化条件在while循环结束后,依然有效。
class WhileTest{
public static void main(String[] args) {
//需求1:遍历50次HelloWorld
int i = 1;
while (i <= 50){
System.out.println("HelloWorld!");
i++; //一定要小心!不要丢了
}
//需求2:遍历1-100以内的偶数,并获取偶数的个数,获取所有的偶数的和
int j = 1;
int count = 0;//记录偶数的个位
int sum = 0;//记录偶数的总和
while (j <= 100){
if (j % 2 == 0){
System.out.println(j);
count++;
sum += j;
}
j++;//真的很容易忘记
}
System.out.println("偶数的个数为:" + count);
System.out.println("偶数的总数为:" + sum);
}
}
案例:
练习1:
随机生成一个100以内的数,猜这个随机数是多少?
从键盘输入数,如果大了,提示大了;如果小了,提示小了;如果对了,就不再猜了,并统计一共猜了多少次。
提示:生成一个[a,b]范围的随机数的方式:(int)(Math.random() * (b - a + 1) + a )
import java.util.Scanner;
class WhileTest1{
public static void main(String[] args){
//1.生成一个[1,100]范围的随机整数
int random = (int)(Math.random() * 100) + 1;
//2.使用Scanner,从键盘上获取数据
Scanner input = new Scanner(System.in);
System.out.println("请输入1-100范围的一个整数:");
int guess = input.nextInt();
//3.声明一个变量,记录猜的次数
int guessConut = 1;
//4.使用循环结构,进行对次循环的对比和获取数据
while (random != guess){
if (random > guess){
System.out.println("猜小了!!");
}else{
System.out.println("猜大了!!");
}
System.out.println("请输入1-100范围的一个整数:");
guess = input.nextInt();
guessConut++;
}
//能结束循环,就意味着random和guess相等了
System.out.println("恭喜你猜对了!!");
System.out.println("共用了" + guessConut + "次");
input.close();//太容易忘记了
}
}
练习2:
世界最高山峰是珠穆朗玛峰,它的高度是8848.86米,假如我有一张足够大的纸,它的厚度是0.1毫米。
请问,我折叠了多少次,可以折成珠穆朗玛峰的高度?
class WhileTest2{
public static void main(String[] args) {
//1.声明珠穆朗玛峰的高度、纸的默认厚度
double paper = 0.1;//单位:毫米
double zf = 8848869;//单位:毫米
//2.定义一个变量,记录折纸的次数
int count = 0;
//3,通过循环结构,不断调整纸的厚度(当纸的厚度超过珠峰高度时,停止循环)
while (paper <= zf){
paper *= 2;
count++;
}
System.out.println("paper的高度为:" + (paper / 1000) + "超出了珠穆朗玛峰的高度" + (zf / 1000) + "米");
System.out.println("共折了" + count + "次");
}
}
1.6循环结构之3:do-while
- 至少会执行一次循环体
- 开发中,使用的较少
基本语法:
循环结构之一:do-while循环
1、凡是循环结构,就一定会有4个要素:
① 初始化条件
② 循环条件 --> 一定是boolean类型的变量或表达式
③ 循环体
④ 迭代部分
2、do-while的格式
①
do{
③
④
}while(②);
执行过程:① - ③ - ④ - ② - ③ - ④ - ... - ②
3、说明:
1)do-while循环至少执行一次循环体。
2)for、while、do-while循环三者之间是可以相互转换的。
3)do-while循环结构,在开发中,相较于for、while循环来讲,使用的较少。
4、对比三种循环结构
① 三种循环结构都是具有四个要素:
循环变量的初始化条件
循环条件
循环体语句块
循环变量的修改的迭代表达式
② 从循环次数角度分析
do-while循环至少执行一次循环体语句
for和while循环先判断循环条件语句是否成立,然后决定是否执行循环体
③ 如何选择
遍历有明显的循环次数(范围)的需求,选择for循环
遍历没有明显的循环次数(范围)的需求,选择while循环
如果循环体语句块至少执行一次,可以考虑使用do-while循环
本质上:三种循环之间完全可以互相转换,都可以实现循环的功能
class DoWhileTest{
public static void main(String[] args) {
//需求:遍历100以内的偶数,并输出偶数的个数和总和
int i = 1;
int count = 0;//记录偶数的个数
int sum = 0;//记录偶数的总和
do{
if (i % 2 == 0){
System.out.println(i);
count++;
sum += i;
}
i++;
}
while (i <= 100);
System.out.println("偶数的个数为" + count);
System.out.println("偶数的总和为" + sum);
//*********************************
//while 和 do-while 的区别
int num1 = 10;
while (num1 > 10){
System.out.println("while hello");
num1--;
}
int num2 = 10;
do{
System.out.println("do-while hello");
num2--;
}
while (num2 > 10);
}
}
案例:
练习1:
题目:模拟ATM取款
声明变量balance并初始化为0,用以表示银行账户的余额,下面通过ATM机程序实现存款,取款等功能。
======ATM======
1、存款
2、取款
3、显示余额
4、退出
请选择(1-4):
import java.util.Scanner;
class DoWhileTest1{
public static void main(String[] args) {
//1.定义balance的变量,记录账户余额
double banlance = 0.0;
boolean flag = true;//控制循环的结束
//2.声明ATM取款的界面
Scanner input = new Scanner(System.in);//实例
do
{
//2.声明ATM取款的界面
System.out.println("======ATM======");
System.out.println(" 1、存款");
System.out.println(" 2、取款");
System.out.println(" 3、显示余额");
System.out.println(" 4、退出");
System.out.println("请选择(1-4):");
//3.使用Scanner获取用户的选择
int choose = input.nextInt();
switch (choose){
//4.根据用户的选择,决定执行存款、取款、显示余额、退出的操作
case 1:
System.out.print("请输入需要存款金额:");
double money = input.nextDouble();
if (money > 0){
banlance += money;
System.out.print("存款成功!!");
}
break;
case 2:
System.out.println("请输入需要取款金额:");
double money1 = input.nextDouble();
if (money1 > 0 && banlance >= money1)
{
banlance -= money1;
System.out.print("取款成功!!");
}else{
System.out.println("您的输入有误或余额不足!");
}
case 3:
System.out.println("您的余额为:" + banlance);
break;
case 4:
System.out.println("感谢使用,欢迎下次再来!!");
flag = false;
break;
default:
System.out.println("您的输入有误,请重新输入!!");
}
}
while (flag);
input.close();
}
}
1.7"无限"循环
基本语法:
"无限"循环结构的使用
1.格式:while(true) 或 for(;;)
2.开发中,有时并不确定需要循环多少次,需要根据循环体内部某些条件,来控制循环的结束(使用break)。
3.如果此循环结构不能终止,则构成了死循环!开发中要避免出现死循环。
class ForWhileTest{
public static void main(String[] args){
/*
while (true){
System.out.println("I love you!");
}
/*
for(;;){
System.out.println("I love you!");
}
*/
//死循环的后面不能有执行语句。
//System.out.println("end");
}
}
案例:
练习1:
案例:从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。
import java.util.Scanner;
class ForWhileTest1{
public static void main(String[] args) {
//1、从键盘中读取整数
Scanner input = new Scanner(System.in);
int positiveCount = 0;//记录正数的个数
int negativeCount = 0;//记录负数的个数
while (true)
{
System.out.println("请输入一个整数(输入0的时候结束程序):");
int num1 = input.nextInt();//获取用户输入的整数
if (num1 > 0){//正数
positiveCount++;
}else if (num1 < 0)//负数
{
negativeCount++;
}else{//输入0
break;
}
}
System.out.println("输入的正数个数为:" + positiveCount);
System.out.println("输入的正数个数为:" + negativeCount);
//关闭
}
}
1.8嵌套循环
基本语法:
嵌套循环的使用
1.嵌套循环:是指一个循环结构A的循环体是另一个循环结构B。
- 外层循环:循环结构A
- 内层循环:循环结构B
2.说明:
1) 内层循环充当了外层循环的循环体
2) 对于两层嵌套循环来说,外层循环控制行数,内层循环控制列数。
3) 举例:外层循环执行m次,内层循环执行n次,则内层循环的循环体共执行m * n次
4) 实际开发中,我们不会出现三层以上的循环结构,三层的循环结构都很少见。
class ForForTest{
public static void main(String[] args) {
//需求1:打印******
for (int i = 0; i <= 5; i++){
System.out.print('*');
}
System.out.println("\n###############");
//需求2:
/*
******
******
******
******
******
*/
//方式1:这两行运行5次
//System.out.print("*");
//System.out.print();
//方式2:
for (int i = 1; i <= 5; i++){
for (int j = 1; j <= 6; j++){
System.out.print("*");
}
System.out.println();//换行
}
//需求3:
/* i(第几行) j(每一行中*的个数)
* 1 1
** 2 2
*** 3 3
**** 4 4
***** 5 5
*/
for (int i = 1; i <= 5; i++){
for (int j = 1; j <= i; j++){
System.out.print('*');
}
System.out.println();
}
//需求4:
/* i(第几行) j(每一行中*的个数) i + j = 6 --> j = 6 - i
***** 1 5 1 + 5 = 6
**** 2 4 2 + 4 = 6
*** 3 3 3 + 3 = 6
** 4 2 4 + 2 = 6
* 5 1 5 + 1 = 6
*/
for (int i = 1; i <= 5; i++){
for (int j = 1; j <= (6-i); j++){
System.out.print('*');
}
System.out.println();
}
//需求3:
/*
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
*/
/* i(第几行) j(每一行中-的个数) k(每行中的*个数) 2*i + j = 10 ———> j = 10 - 2*i //注:这里的2就是逐行减少2个'-'
--------* 1 8 1 k = 2*i -1
------* * * 2 6 3
----* * * * * 3 4 5
--* * * * * * * 4 2 7
* * * * * * * * * 5 0 9
--* * * * * * * 1 2 7 2*i = j ———> j = 2*i //注:这里的2就是逐行减少2个'-'
----* * * * * 2 4 5 k + 2*i = 9 ———> k = 9 - 2*i //注:这里的2就是逐行减少2个'-'
------* * * 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();
}
}
}
案例:
练习1:
练习:九九乘法表
class NineNineTable{
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();
}
}
}
1.9关键字break、continue
- break在开发中常用;而continue较少使用
- 笔试题:break和continue的区别。
基本语法:
1.break和continue关键字的使用
使用范围 在循环结构中的作用 相同点
break: switch-case
循环结构中 结束(或跳出)当前循环结构 在此关键字的后面不能声明执行语句
continue 循环结构中 结束(或跳出)当次循环 在此关键字的后面不能声明执行语句
2. 了解带标签的break和continue的使用
3. 开发中,break的使用频率要远高于continue。
class BreakContinueTest{
public static void main(String[] args) {
for (int j = 1; j <= 4; j++){
for (int i = 1; i <= 10; i++){
if (i % 4 == 0){
//break;//输出1行123,注:break是跳出离break最近的一次循环
continue;//输出4行123567910,注:continue是执行当这一句之后不执行,直接进入i++
//在break后面加语句的话,编译不通过
//System.out.println("今晚上迪丽热巴要约我!"); // 错误: 无法访问的语句
}
System.out.print(i);
}
System.out.println();
}
System.out.println();//因为上面没有换行
//*************************
//了解一下:标签
label:for (int j = 1; j <=4 ; j++){
for (int i = 1; i <= 10; i++){
if (i % 4 == 0){
//break;//输出4行123,
//break label;//输出1行123
//continue;//输出4行123567910
continue label;//输出1行123,但是123出现4次
}
System.out.print(i);
}
System.out.println();
}
}
}
1.10项目1:谷粒记账软件
- 特点1:代码量更大,逻辑更复杂 -->推荐大家一定写一写,而且多写几遍。
- 特点2:内部不包含新的知识点。 --->不太着急写。
阶段一的项目:谷粒记账软件的实现
import java.util.Scanner;
class GuLiAccount{
public static void main(String[] args) {
boolean isFlag = true;//控制循环的结束
String info = "";//记录收支信息
//初始金额
int balance = 10000;
while (isFlag){
System.out.println("-----------------谷粒记账软件-----------------\n");
System.out.println(" 1 收支明细");
System.out.println(" 2 登记收入");
System.out.println(" 3 登记支出");
System.out.println(" 4 退 出\n");
System.out.print(" 请选择(1-4):\n");
char choose = Utility.readMenuSelection();//获取用户的选择:'1','2','3','4'
switch (choose){
case '1':
System.out.println("-----------------当前收支明细记录-----------------\n");
System.out.println("收支\t账户金额\t收支金额\t说 明\n");
System.out.println(info"\n");
System.out.println("--------------------------------------------------");
break;
case '2':
System.out.print("本次收入金额:\n");
int money1 = Utility.readNumber();
System.out.print("本次收入说明:\n");
int addDsec = Utility.readString();
if (money1 > 0) {
balance += money1;
}
System.out.println("---------------------登记完成---------------------");
info = "收入" + "\t" + balance + "\t" + money1 + "\t" + addDsec;
break;
case '3':
System.out.print("本次支出金额:\n");
int money2 = Utility.readNumber();
System.out.print("本次支出说明:\n");
int miunDsec = Utility.readString();
if (money2 > 0 && balance >= money2){
balance -= money2;
}
System.out.println("---------------------登记完成---------------------");
info = "收入" + "\t" + balance + "\t" + money2 + "\t" + miunDsec;
break;
case '4':
System.out.print("确认是否退出(Y/N):");
char isAnswer = Utility.readConfirmSelection();
if (isAnswer == 'Y'){
isFlag = false;
break;
}else if (isAnswer == 'N'){
break;
}else{
System.out.println("您的输入有误!!");
break;
}
default:
System.out.println("您的输入有误,请重新选择!!");
}
}
}
}
使用的包
import java.util.Scanner;
/**
Utility工具类:
将不同的功能封装为方法,就是可以直接通过调用方法使用它的功能,而无需考虑具体的功能实现细节。
*/
public class Utility {
private static Scanner scanner = new Scanner(System.in);
/**
用于界面菜单的选择。该方法读取键盘,如果用户键入’1’-’4’中的任意字符,则方法返回。返回值为用户键入字符。
*/
public static char readMenuSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1);
c = str.charAt(0);
if (c != '1' && c != '2' && c != '3' && c != '4') {
System.out.print("选择错误,请重新输入:");
} else break;
}
return c;
}
/**
用于收入和支出金额的输入。该方法从键盘读取一个不超过4位长度的整数,并将其作为方法的返回值。
*/
public static int readNumber() {
int n;
for (; ; ) {
String str = readKeyBoard(4);
try {
n = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.print("数字输入错误,请重新输入:");
}
}
return n;
}
/**
用于收入和支出说明的输入。该方法从键盘读取一个不超过8位长度的字符串,并将其作为方法的返回值。
*/
public static String readString() {
String str = readKeyBoard(8);
return str;
}
/**
用于确认选择的输入。该方法从键盘读取‘Y’或’N’,并将其作为方法的返回值。
*/
public static char readConfirmSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1).toUpperCase();
c = str.charAt(0);
if (c == 'Y' || c == 'N') {
break;
} else {
System.out.print("选择错误,请重新输入:");
}
}
return c;
}
private static String readKeyBoard(int limit) {
String line = "";
while (scanner.hasNext()) {
line = scanner.nextLine();
if (line.length() < 1 || line.length() > limit) {
System.out.print("输入长度(不大于" + limit + ")错误,请重新输入:");
continue;
}
break;
}
return line;
}
}
1.11Scanner类的使用
基本语法:
如何从键盘获取不同类型(基本数据类型、String类型)的变量:使用Scanner类。
1.使用Scanner获取不同类型数据的步骤
步骤1:导包import java.util.Scanner;
步骤2:提供(或创建)一个Scanner类的实例
步骤3:调用Scanner类中的方法,获取指定类型的变量(nextXxx())
步骤4:关闭资源,调用Scanner类的close()
2.案例:小明注册某交友网站,要求录入个人相关信息。如下:
请输入你的网名、你的年龄、你的体重、你是否单身、你的性别等情况。
3.Scanner类中提供了获取byte \ short \ int \long \ float \ double \ boolean \ String类型变量的方法。
注意,没有提供获取char类型变量的方法。需要使用next().charAt(0);
4.查看Scanner类的地址为:file:///F:/java/06_%E8%BD%AF%E4%BB%B6%E4%B8%8E%E8%B5%84%E6%96%99/06_%E8%BD%AF%E4%BB%B6%E4%B8%8E%E8%B5%84%E6%96%99/05-%E8%B5%84%E6%96%99/API%E6%96%87%E6%A1%A3/jdk-17.0.2_doc-all/docs/api/java.base/java/util/Scanner.html
//步骤1:导包 import java.util.Scanner;
import java.util.Scanner;
class ScannerTest{
public static void main(String[] args) {
//步骤2:提供(或创建)一个Scanner类的实例
Scanner scan = new Scanner(System.in);
System.out.println("欢迎光临你来我往交友网");
System.out.println("请输入你的网名:");
//步骤3:调用Scanner类中的方法,获取指定类型的变量
String name = scan.next(); //在终端获取名字,利用.next()方法将名字赋给变量name
System.out.println("请输入你的年龄:");
int age = scan.nextInt();
System.out.println("请输入你的体重:");
double weight = scan.nextDouble();
System.out.println("你是否单身(单身:true;不单身:false):");
boolean isSingle = scan.nextBoolean();
System.out.println("请输入你的性别:(男\\女):");
char gender = scan.next().charAt(0);
System.out.println("网名:" + name + ",年龄:" + age + ",体重" + weight + ",是否单身" + isSingle + ",性别" + gender);
System.out.println("注册完成,欢迎继续进入体验!");
//步骤4:关闭资源,调用Scanner类的close()
scan.close();
}
}
案例:
练习1:
大家都知道,男大当婚,女大当嫁。那么女方家长要嫁女儿,当然要提出一定的条件:高:180cm以上;富:财富1千万以上;帅:是。
如果这三个条件同时满足,则:“我一定要嫁给他!!!”
如果这三个条件有为真的情况,则:“嫁吧,比上不足,比下有余。”
如果三个条件都不满足,则:“不嫁!”
import java.util.Scanner;
class ScannerExer{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入你的身高(cm):");
int height = scan.nextInt();
System.out.println("请输入你的财富(一千万为单位):");
double wealth = scan.nextDouble();
/*
方式1:关于是否帅问题,我们使用boolean类型接收
System.out.println("帅否?(true/false)");
boolean isHangsome = scan.nextBoolean();
//判断
if (height == 180 && wealth >= 1.0 && isHangsome == true){//知识点:判断两个字符串是否相等,使用String的equals()
System.out.println("我一定要嫁给他");
}else if (height == 180 || wealth >= 1.0 || isHangsome == true){
System.out.println("嫁吧,比上不足,比下有余");
}else{
System.out.println("不嫁!");
}
*/
//方式2:关于是否帅,我们使用String类型接收
System.out.println("帅否?(是/否):");
String isHangsome = scan.next();
//判断
if (height >= 180 && wealth >= 1.0 && "是".equals(isHangsome)){//知识点:判断两个字符串是否相等,使用String的equals()
System.out.println("我一定要嫁给他");
}else if (height == 180 || wealth >= 1.0 || "是".equals(isHangsome)){
System.out.println("嫁吧,比上不足,比下有余");
}else{
System.out.println("不嫁!");
}
//关闭资源
scan.close();
}
}
1.12获取随机数
基本语法:
如何获取一个随机数?
1.可以使用Java提供的API:Math类的random()
2.random()调用以后,会返回一个[0.0,1.0)范围的double型的随机数
3.需求1:获取一个[0,100]范围的随机整数?
需求2:获取一个[1,100]范围的随机整数?
4.需求:获取一个[a,b]范围的随机整数?
int(Math.random() * (b - a + 1)) + a
class RandomTest{
public static void main(String[] args) {
double d1 = Math.random();
System.out.println("d1 = " + d1);
int num1 = (int)(Math.random() * 101); //[0.0,1.0) ---> [0.0,101.0) ---> [0,100]
System.out.println("num1 = " + num1);
int num2 = (int)(Math.random() * 100) + 1; //[0.0,1.0) ---> ---> [0.0,100.0) ---> [0,99] ---> [1,100]
System.out.println("num1 = " + num2);
}
}
1.13体会算法的魅力
基本实现功能:
题目:找出100以内的所有的素数(质数)?100000以内呢?
质数:只能被1和它本身整除的自然数。比如:2,3,5,7,11,13,17,19,23...
-->换句话说,从2开始到这个自然数-1为止,不存在此自然数的约数。
class PrimeNumberTest{
public static void main(String[] args) {
//方式1:利用约数的个数为0,来判断
for (int i = 2; i <= 100; i++){//遍历100以内的自然数
int number = 0;//记录i的约数的个数(从2开始,到i-1为止)。注:如果number定义在外层for之外,就应该在外层for之内进行重置
//判定i是否是质数
for (int j = 2; j < i; j++){
if (i % j == 0){
number++;
}
}
if (number == 0){
System.out.println(i);
}
}
System.out.println("**********************************");
//方式2:设置一个小旗子
for (int i = 2; i <= 100; i++){
boolean isFlag = true;
for (int j = 2; j < i; j++){
if (i % j == 0){
isFlag = false;
}
}
if (isFlag){
System.out.println(i);
}
}
System.out.println("**********************************");
//方式3:设置一个小旗子,但是需要重置
boolean isFlag = true;
for (int i = 2; i <= 100; i++){
for (int j = 2; j < i; j++){
if (i % j == 0){
isFlag = false;
}
}
if (isFlag){
System.out.println(i);
}
isFlag = true;
}
}
}
测试性能:
实现方式1:
遍历100000以内的所有的质数。体会不同的算法实现,其性能的差别
此PrimeNumberTest1.java是实现方式1
class PrimeNumberTest1{
public static void main(String[] args) {
//获取系统当前的时间:
long start = System.currentTimeMillis();
int number = 0;//记录质数的个数
//遍历100000以内的自然数
for (int i = 2; i <= 100000; i++){
boolean isFlag = true;
//判断i是否是质数
for (int j = 2; j < i; j++){
if (i % j == 0){
isFlag = false;
}
}
if (isFlag){
number++;
}
}
//获取系统当前的时间:
long end = System.currentTimeMillis();
System.out.println("质数的总个数为:" + number);//个数为:9592
System.out.println("花费的时间为:" + (end - start));//时间为(ms):14382
}
}
实现方式2:
遍历100000以内的所有的质数。体会不同的算法实现,其性能的差别
此PrimeNumberTest2.java是实现方式2.针对于PrimeNumberTest1.java中算法的优化
class PrimeNumberTest2{
public static void main(String[] args) {
//获取系统当前的时间:
long start = System.currentTimeMillis();
int number = 0;//记录质数的个数
//遍历100000以内的自然数
for (int i = 2; i <= 100000; i++){
boolean isFlag = true;
//判断i是否是质数
for (int j = 2; j < Math.sqrt(i); j++){//举个例子:100,除以2等于50,就没有必要除以50了,怎么找不会重复除的哪个数呢?就是100除以这个数等于这个数本身
if (i % j == 0){
isFlag = false;
break; //遇到一个约数就退出,节省时间,针对非质数有效果
}
}
if (isFlag){
number++;
}
}
//获取系统当前的时间:
long end = System.currentTimeMillis();
System.out.println("质数的总个数为:" + number);//个数为:9592
System.out.println("花费的时间为:" + (end - start));//时间为(ms):14382 ---> 17(效果是一样,但是非常节省时间)
}
}
二、企业真题
1.break和continue的作用
break只能在switch-case循环结构中用。结束(或跳出)当前寻结构
continue在循环结构中用。结束(或跳出)当次循环
2.if分支语句和switch分支语句的异同之处
- if-else语句优势
- if语句的条件是一个布尔类型值,if条件表达式为true则进入分支,可以用于范围的判断,也可以用于等值的判断,使用范围更广。
- switch语句的条件是一个常量值(byte,short,int,char,枚举,String),只能判断某个变量或表达式的结果是否等于某个常量值,使用场景较狭窄。
- switch语句优势
- 当条件是判断某个变量或表达式是否等于某个固定的常量值时,使用if和switch都可以,习惯上使用switch更多。因为效率稍高。当条件是区间范围的判断时,只能使用if语句。
- 使用switch可以利用穿透性,同时执行多个分支,而if...else没有穿透性。
3.什么时候用语句if,什么时候选用语句switch
同上
4.switch语句中忘记写break会发生什么
case穿透
5.Java支持哪些类型循环
- for;while;do-while
- 增强for(或foreach),放到集合中讲解
6.while和do while循环的区别
- do-while至少会执行一次。