第2章、基本语法(下):程序流程控制

(1)流程控制语句是用来控制程序中各语句执行顺序的语句,可以把语句组合成能完成一定功能的小逻辑模块。
(2)其流程控制方式采用结构化程序设计中规定的三种基本流程结构,即:
- 顺序结构
- 分支结构
- 循环结构
1、顺序结构
程序从上到下逐行地执行,中间没有任何判断和跳转。

Java中定义成员变量时采用合法的前向引用
。如:
public class Test{ int num1 = 12; int num2 = num1 + 2; }
错误形式:
public class Test{ int num2 = num1 + 2;//编译不通过 int num1 = 12; }
2、分支结构
根据条件,选择性地执行某段代码。
有if-else
和 switch-case
两种分支语句。
(1)分支语句1:if-else结构
if语句有三种格式:
第一种:

if(条件表达式){ 执行表达式; }
示例
public class BranchingStructureTest { public static void main(String[] args) { //举例一 int hartBeats = 89;//心跳 if(hartBeats < 60 || hartBeats > 100){ System.out.println("需要进一步进行检查..."); } System.out.println("检查结束"); //举例二 int age = 23; if (age < 18){ System.out.println("未成年..."); }else { System.out.println("成年了..."); } //举例三 if (age < 0){ System.out.println("输入的数据不合理..."); }else if (age < 18){ System.out.println("青少年..."); }else if (age < 35){ System.out.println("青壮年时期..."); }else if (age < 60){ System.out.println("中年"); }else if (age < 120){ System.out.println("老年人..."); }else { System.out.println("成仙了..."); } } }
第二种:

if(条件表达式){ 执行表达式1; }else{ 执行表达式2; }
示例:
public class BranchingStructureTest { public static void main(String[] args) { int age = 23; if (age < 18){ System.out.println("未成年..."); }else { System.out.println("成年了..."); } //举例三 if (age < 0){ System.out.println("输入的数据不合理..."); }else if (age < 18){ System.out.println("青少年..."); }else if (age < 35){ System.out.println("青壮年时期..."); }else if (age < 60){ System.out.println("中年"); }else if (age < 120){ System.out.println("老年人..."); }else { System.out.println("成仙了..."); } } }
第三种:

if(条件表达式){ 执行表达式1; }else if(条件表达式){ 执行表达式2 }else if(条件表达式){ 执行表达式3; }... else{ 执行表达式n; }
示例:
public class BranchingStructureTest { public static void main(String[] args) { if (age < 0){ System.out.println("输入的数据不合理..."); }else if (age < 18){ System.out.println("青少年..."); }else if (age < 35){ System.out.println("青壮年时期..."); }else if (age < 60){ System.out.println("中年"); }else if (age < 120){ System.out.println("老年人..."); }else { System.out.println("成仙了..."); } } }
分支结构:if-else使用说明
- 条件表达式必须是布尔表达式(关系表达式或逻辑表达式)、布尔变量
- 语句块只有一条执行语句时,一对{}可以省略,但建议保留
- if-else语句结构,根据需要可以嵌套使用
- 当if-else结构是“多选一”时,最后的else是可选的,根据需要可以省略
- 当多个条件是“互斥”关系时,条件判断语句及执行语句间顺序无所谓
- 当多个条件是“包含”关系时,“小上大下 / 子上父下”
if-else的练习
练习1
import java.util.Scanner; public class Test1 { public static void main(String[] args) { /* 岳小鹏参加Java考试,他和父亲岳不群达成承诺: 如果: 成绩为100分时,奖励一辆BMW; 成绩为(80,99]时,奖励一台iphone xs max; 当成绩为[60,80]时,奖励一个 iPad; 其它时,什么奖励也没有。 请从键盘输入岳小鹏的期末成绩,并加以判断 */ /** * 说明: * 1、else结构时可选的。 * 2、针对与条件表达式 * 如果多个条件表达式之间是 “互斥”关系,哪个判断和和执行语句声明在上面还是下面,无所谓。 * 如果多个条件表达式之间有交集的关系,需要根据实际情况,考虑清楚应该将哪个结构声明在上面。 * 如果多个条件表达式之间有包含关系,通常情况下,需要将范围小的声明在声明大的上面。否则,范围小的就没机会执行了。 */ System.out.print("请输入分数:(0-100)"); Scanner scanner = new Scanner(System.in); double score = scanner.nextDouble(); if (score == 100){ System.out.println("奖励一辆BMW"); }else if (score > 80 && score <= 99){ System.out.println("奖励一台iphone xs max"); }else if (score > 60 && score <= 80){ System.out.println("奖励一个 iPad"); }else { System.out.println("什么奖励也没有"); } } }
练习2
import java.util.Scanner; public class Test2 { public static void main(String[] args) { /* 编写程序:由键盘输入三个整数分别存入变量num1、num2、num3, 对它们进行排序(使用 if-else if-else),并且从小到大输出。 说明: 1、if-else结构是可以互相嵌套的。 2、如果if-else结构种中的执行语句只有一行时,对应的一堆{}是可以省略的,但是不建议这样做。 */ Scanner scanner = new Scanner(System.in); System.out.print("请输入第一个数:"); int number1 = scanner.nextInt(); System.out.print("请输入第一个数:"); int number2 = scanner.nextInt(); System.out.print("请输入第一个数:"); int number3 = scanner.nextInt(); // if (number1 > number2 && number1 > number3){ // if (number2 > number3){ // System.out.println(number3 + ", " + number2 + ", " + number1); // }else { // System.out.println(number2 + ", " + number3 + ", " + number1); // } // }else if (number2 > number1 && number2 > number3){ // if (number1 > number3){ // System.out.println(number3 + ", " + number1 + ", " + number2); // }else { // System.out.println(number1 + ", " + number3 + ", " + number2); // } // }else { // if (number1 > number2){ // System.out.println(number2 + ", " + number1 + ", " + number3); // }else { // System.out.println(number1 + ", " + number2 + ", " + number3); // } // } //先比较其中两个,剩下的数只有三个位置,要么最左边,要么中间,要么最右边 if (number1 >= number2){ if (number3 > number1){ System.out.println(number1 + ", " + number2 + ", " + number3); }else if (number3 > number2 && number3 < number1){ System.out.println(number1 + ", " + number3 + ", " + number2); }else { System.out.println(number3 + ", " + number1+ ", " + number2); } }else { if (number3 > number2){ System.out.println(number1 + ", " + number2 + ", " + number3); }else if (number3 < number1){ System.out.println(number3 + ", " + number2 + ", " + number1); }else { System.out.println(number1 + ", " + number3 + ", " + number2); } } } }
练习3
public class Test3 { public static void main(String[] args) { //第一题:对下列代码,若有输出,指出输出结果。 int x = 4; int y = 1; if (x > 2){ if (y > 2) System.out.println(x + y); System.out.println("atGuiGu"); }else System.out.println("x is " + x); //第二题:编译是否有问题,若没有问题,指出输出结果。 int i = 4; int j = 1; if (i > 2) if (j > 2) System.out.println(i + j); //System.out.println("atGuiGu"); else System.out.println("x is " + i); //第三题: boolean b = true; //如果写成if(b=false)能编译通过吗?如果能,结果是? if(b == false) System.out.println("a"); else if(b) System.out.println("b"); else if(!b) System.out.println("c"); else System.out.println("d"); } }
练习4
import java.util.Scanner; public class Test4 { public static void main(String[] args) { //第一题:编写程序,声明2个int型变量并赋值。判断两数之和,如果大于等于50,打印“hello world!” int a = 20; int b = 30; if (a + b >= 50){ System.out.println("hello world!"); } //第二题:编写程序,声明2个double型变量并赋值。判断第一个数大于10.0,且第2个数小于20.0,打印两数之和。否则,打印两数的乘积。 double d1 = 10.0; double d2 = 20.0; if (d1 > 10.0 && d2 < 20.0){ System.out.println("d1 + d2 = " + (d1 + d2)); }else { System.out.println("d1 * d2 = " + (d1 * d2)); } } }
练习5
import java.util.Scanner; public class Test5 { public static void main(String[] args) { /* 我家的狗5岁了,5岁的狗相当于人类多大呢?其实,狗的前两年每 一年相当于人类的10.5岁,之后每增加一年就增加四岁。那么5岁的狗 相当于人类多少年龄呢?应该是:10.5 + 10.5 + 4 + 4 + 4 = 33岁。 编写一个程序,获取用户输入的狗的年龄,通过程序显示其相当于人类的年龄。如果用户输入负数,请显示一个提示信息。 */ Scanner scanner = new Scanner(System.in); System.out.print("请输入小狗的年龄:"); double dogAge = scanner.nextInt(); double peopleAge; if (dogAge < 0){ System.out.println("输入的年龄不合法!"); }else if (dogAge <= 2){ peopleAge = dogAge * 10.5; System.out.println(dogAge + "岁的狗狗相当于人类" + peopleAge + "的年龄"); }else { peopleAge = 2 * 10.5 + (dogAge -2) * 4; System.out.println(dogAge + "岁的狗狗相当于人类" + peopleAge + "的年龄"); } } }
练习6
import java.util.Scanner; public class Test6 { public static void main(String[] args) { /* 假设你想开发一个玩彩票的游戏,程序随机地产生一个两位数的彩票,提示用户输入一个两位数,然后按照下面的规则判定用户是否能赢。 1)如果用户输入的数匹配彩票的实际顺序,奖金10 000美元。 2)如果用户输入的所有数字匹配彩票的所有数字,但顺序不一致,奖金 3 000美元。 3)如果用户输入的一个数字仅满足顺序情况下匹配彩票的一个数字,奖金1 000美元。 4)如果用户输入的一个数字仅满足非顺序情况下匹配彩票的一个数字,奖金500美元。 5)如果用户输入的数字没有匹配任何一个数字,则彩票作废。 提示:使用(int)(Math.random() * 90 + 10)产生随机数。 Math.random() : [0,1) * 90 [0,90) + 10 [10,100) [10,99] 公式:[a,b) (int)(Math.random() * (b - a + 1) + a) */ Scanner scanner = new Scanner(System.in); System.out.print("请输入一个两位数:"); int number = scanner.nextInt(); int result = (int)(Math.random() * 90 + 10);//彩票号码 System.out.println("中奖号码:" + result); int singlePut = number % 10;//输入的个位数 int tensPut = number / 10;//输入的十位数 int singleResult = result % 10;//彩票号码的个位数 int tensResult = result /10;//彩票号码的十位数 if (number == result){ System.out.println("奖金10 000美元"); }else if (singlePut == tensResult && tensPut == singleResult){ System.out.println("奖金3 000美元"); }else if (singlePut == singleResult || tensPut == tensResult){ System.out.println("奖金1 000美元"); }else if (singlePut == tensResult || tensPut == singleResult){ System.out.println("奖金500美元"); }else { System.out.println("彩票作废"); } } }
练习7
import java.util.Scanner; public class Test7 { public static void main(String[] args) { /* 大家都知道,男大当婚,女大当嫁。那么女方家长要嫁女儿,当然要提出一定的条件:高:180cm以上;富:财富1千万以上;帅:是。 如果这三个条件同时满足,则:“我一定要嫁给他!!!” 如果三个条件有为真的情况,则:“嫁吧,比上不足,比下有余。” 如果三个条件都不满足,则:“不嫁!” 提示: Sysout(“身高: (cm)) scanner.nextInt(); Sysout(“财富: (千万)) scanner.nextDouble(); Sysout(“帅否: (true/false)) (是/否) scanner.nextBoolean(); scanner.next(); “是”.equals(str) */ Scanner scanner = new Scanner(System.in); System.out.print("身高(cm):"); int height = scanner.nextInt(); System.out.print("财富(千万):"); double money = scanner.nextDouble(); // System.out.print("帅否(true/false):"); // boolean isHandsome = scanner.nextBoolean(); System.out.print("帅否(是/否):"); String isHandsome = scanner.next(); // if (height > 180 && money > 1 && isHandsome){ // System.out.println("我一定要嫁给他!!!"); // }else if (height > 180 || money > 1 || isHandsome){ // System.out.println("嫁吧,比上不足,比下有余。"); // }else { // System.out.println("不嫁!"); // } if (height > 180 && money > 1 && isHandsome.equals("是")){ System.out.println("我一定要嫁给他!!!"); }else if (height > 180 || money > 1 || isHandsome.equals("是")){ System.out.println("嫁吧,比上不足,比下有余。"); }else { System.out.println("不嫁!"); } } }
(2)分支语句2:switch-case结构

switch(表达式){ case 常量1: 语句1; break; case 常量2: 语句2; break; ... case 常量N: 语句N; break; default: 语句; break; }
switch语句应用举例
public class BranchingStructureTest { public static void main(String[] args) { int number = 1; // 当调用完执行语句以后,仍然继续向下执行其它case结构中的执行语句 switch (number){ case 1: System.out.println("one"); case 2: System.out.println("two"); case 3: System.out.println("three"); case 4: System.out.println("four"); default: System.out.println("other"); } System.out.println("--------------------------------------"); //遇到break关键字,跳出switch-case结构 switch (number){ case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; case 3: System.out.println("three"); break; case 4: System.out.println("four"); break; default: System.out.println("other"); break; } //编译不通过 boolean类型不可以用作switch-case中的表达式 // boolean isHandsome = true; // switch (isHandsome){ // case true: // System.out.println("我好帅呀..."); // break; // case false: // System.out.println("我好丑呀..."); // break; // default: // System.out.println("输入有误..."); // break; // } System.out.println("--------------------------------------"); String season = "autumn"; switch(season){ case "spring": System.out.println("春暖花开"); break; case "summer": System.out.println("夏日炎炎"); break; case "autumn": System.out.println("秋高气爽"); break; case "winter": System.out.println("冬雪皑皑"); break; default: System.out.println("季节输入有误"); break; } System.out.println("--------------------------------------"); //会输出 “季节输入有误” 和 “春暖花开”,但是实际中也不会去这么写。 season = "1"; switch(season){ default: System.out.println("季节输入有误"); //break; case "spring": System.out.println("春暖花开"); break; case "summer": System.out.println("夏日炎炎"); break; case "autumn": System.out.println("秋高气爽"); break; case "winter": System.out.println("冬雪皑皑"); break; } //case后面声明的不是常量 编译不通过 // int age = 20; // switch (age){ // case age > 18: // System.out.println("成年了"); // break; // default: // System.out.println("未成年"); // break; // } } }
switch语句有关规则
switch(表达式)中表达式的值必须是下述几种类型之一:byte,short,char,int,枚举 (jdk 5.0),String (jdk 7.0);
case子句中的值必须是常量,不能是变量名或不确定的表达式值;
同一个switch语句,所有case子句中的常量值互不相同;
break语句用来在执行完一个case分支后使程序跳出switch语句块;如果没有break,程序会顺序执行到switch结尾;
default子句是可任选的。同时,位置也是灵活的。当没有匹配的case时,执行default;
switch的练习
练习1
import java.util.Scanner; /** * @author: huxingxin * @date: 2022/11/16 14:20:32 * @description: */ public class Test1 { public static void main(String[] args) { /* 1.使用 switch 把小写类型的 char型转为大写。只转换 a, b, c, d, e. 其它的输出 “other”。 提示:String word = scan.next(); char c = word.charAt(0); switch(c){} */ Scanner scanner = new Scanner(System.in); System.out.print("请输入一个小写字母:"); String word = scanner.next(); char c = word.charAt(0); switch (c){ case 'a': System.out.println("a: A"); break; case 'b': System.out.println("b: B"); break; case 'c': System.out.println("c: C"); break; case 'd': System.out.println("d: D"); break; case 'e': System.out.println("e: E"); break; default: System.out.println("other"); break; } } }
练习2
/** * @author: huxingxin * @date: 2022/11/17 16:20:48 * @description: */ public class Test2 { public static void main(String[] args) { //对学生成绩大于等于60分的,输出“合格”。低于60分的,输出“不合格”。 int score = 8; // switch (score){ // case 0: // System.out.println("不合格"); // break; // ''' // case 60: // System.out.println("合格"); // break; // ... // default: // } // if (score < 60){ // System.out.println("不合格"); // }else { // System.out.println("合格"); // } // 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; // } switch (score/60){ case 0: System.out.println("不合格"); break; case 1: System.out.println("合格"); break; default: System.out.println("输入有误"); break; } //根据用于指定月份,打印该月份所属的季节。 //3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季 int season = 12; switch (season){ case 12: case 1: case 2: System.out.println("冬季"); break; case 3: case 4: case 5: System.out.println("春季"); break; case 6: case 7: case 8: System.out.println("夏季"); break; case 9: case 10: case 11: System.out.println("秋季"); break; default: System.out.println("输入有误"); break; } } }
练习3
import java.util.Scanner; /** * @author: huxingxin * @date: 2022/11/17 16:28:32 * @description: */ public class Test3 { public static void main(String[] args) { /* 编写程序:从键盘上输入2019年的“month”和“day”,要求通过程序 输出输入的日期为2019年的第几天。 */ Scanner scanner = new Scanner(System.in); System.out.print("请输入month:"); int month = scanner.nextInt(); System.out.print("请输入day:"); int day = scanner.nextInt(); // switch (month){ // case 1: // if (day <= 31 && day >= 1){ // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 2: // if (day <= 28 && day >= 1){ // day = 31 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 3: // if (day <= 31 && day >= 1){ // day = 31 + 28 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 4: // if (day <= 30 && day >= 1){ // day = 31 * 2 + 28 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 5: // if (day <= 31 && day >= 1){ // day = 31 * 2 + 28 + 30 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 6: // if (day <= 30 && day >= 1){ // day = 31 * 3 + 28 + 30 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 7: // if (day <= 31 && day >= 1){ // day = 31 * 3 + 28 + 30 * 2 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 8: // if (day <= 31 && day >= 1){ // day = 31 * 4 + 28 + 30 * 2 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 9: // if (day <= 30 && day >= 1){ // day = 31 * 5 + 28 + 30 * 2 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 10: // if (day <= 31 && day >= 1){ // day = 31 * 5 + 28 + 30 * 3 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 11: // if (day <= 30 && day >= 1){ // day = 31 * 6 + 28 + 30 * 3 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 12: // if (day <= 31 && day >= 1){ // day = 31 * 6 + 28 + 30 * 4 + day; // System.out.println("日期为2019年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // default: // System.out.println("输入有误"); // break; // } 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: System.out.println("日期为2019年的第" + day + "天"); default: System.out.println("输入有误"); } } }
练习4
import java.util.Scanner; /** * @author: huxingxin * @date: 2022/11/17 16:28:32 * @description: */ public class Test4 { public static void main(String[] args) { /* 编写程序:从键盘分别输入年、月、日,判断这一天是当年的第几天 注:判断一年是否是闰年的标准: 1)可以被4整除,但不可被100整除 或 2)可以被400整除 */ Scanner scanner = new Scanner(System.in); System.out.print("请输入year:"); int year = scanner.nextInt(); System.out.print("请输入month:"); int month = scanner.nextInt(); System.out.print("请输入day: "); int day = scanner.nextInt(); int februaryDays = 28; if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){ februaryDays = 29; } // switch (month){ // case 1: // if (day <= 31 && day >= 1){ // day = day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 2: // if (day <= februaryDays && day >= 1){ // day = 31 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 3: // if (day <= 31 && day >= 1){ // day = 31 + februaryDays + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 4: // if (day <= 30 && day >= 1){ // day = 31 * 2 + februaryDays + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 5: // if (day <= 31 && day >= 1){ // day = 31 * 2 + februaryDays + 30 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 6: // if (day <= 30 && day >= 1){ // day = 31 * 3 + februaryDays + 30 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 7: // if (day <= 31 && day >= 1){ // day = 31 * 3 + februaryDays + 30 * 2 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 8: // if (day <= 31 && day >= 1){ // day = 31 * 4 + februaryDays + 30 * 2 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 9: // if (day <= 30 && day >= 1){ // day = 31 * 5 + februaryDays + 30 * 2 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 10: // if (day <= 31 && day >= 1){ // day = 31 * 5 + februaryDays + 30 * 3 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 11: // if (day <= 30 && day >= 1){ // day = 31 * 6 + februaryDays + 30 * 3 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // case 12: // if (day <= 31 && day >= 1){ // day = 31 * 6 + februaryDays + 30 * 4 + day; // System.out.println("日期为" + year + "年的第" + day + "天"); // }else { // System.out.println("输入有误"); // } // break; // default: // System.out.println("输入有误"); // break; // } 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 += februaryDays; case 2: day += 31; case 1: System.out.println("日期为" + year + "年的第" + day + "天"); default: System.out.println("输入有误"); } } }
练习5
/** * @author: huxingxin * @date: 2022/11/18 11:36:31 * @description: */ public class Test5 { public static void main(String[] args) { //使用switch语句改写下列if语句: /* int a = 3; int x = 100; if(a==1) x+=5; else if(a==2) x+=10; else if(a==3) x+=16; else x+=34; System.out.println("x = " + x); */ int a = 3; int x = 100; switch (a){ case 1: x += 5; break; case 2: x += 10; break; case 3: x += 16; break; default: x += 34; break; } System.out.println("x = " + x); } }
练习6
import java.util.Scanner; /** * @author: huxingxin * @date: 2022/11/18 15:13:13 * @description: */ public class Test6 { public static void main(String[] args) { /* 编写一个程序,为一个给定的年份找出其对应的中国生肖。中国的生肖基于12年一个周期, 每年用一个动物代表:rat、ox、tiger、rabbit、dragon、snake、horse、sheep、monkey、rooster、dog、pig。 提示:2019年:猪 2019 % 12 == 3 */ Scanner scanner = new Scanner(System.in); System.out.print("请输入年份:"); int year = scanner.nextInt(); String animal = ""; switch (year % 12){ case 1: animal = "rooster(鸡)"; break; case 2: animal = "dog(狗)"; break; case 3: animal = "pig(猪)"; break; case 4: animal = "rat(鼠)"; break; case 5: animal = "ox(牛)"; break; case 6: animal = "tiger(虎)"; break; case 7: animal = "rabbit(兔)"; break; case 8: animal = "dragon(龙)"; break; case 9: animal = "snake(蛇)"; break; case 10: animal = "horse(马)"; break; case 11: animal = "sheep(羊)"; break; case 12: animal = "monkey(猴)"; break; default: break; } System.out.println(year + "年是 " + animal + " 年"); } }
(3)switch和if语句的对比
if和switch语句很像,具体什么场景下,应用哪个语句呢?
- 如果判断的具体数值不多,而且符合byte、short 、char、int、String、枚举等几种类型。虽然两个语句都可以使用,建议使用swtich语句。因为效率稍高。
- 其他情况:对区间判断,对结果为boolean类型判断,使用if,if的使用范围更广。也就是说,使用switch-case的,都可以改写为if-else。反之不成立。
3、循环结构
根据循环条件,重复性的执行某段代码。
有while、do…while、for三种循环语句。
注:JDK1.5提供了foreach循环,方便的遍历集合、数组元素
(1)循环结构
在某些条件满足的情况下,反复执行特定代码的功能
(2)循环语句分类
- for 循环
- while 循环
- do-while 循环
(3)循环语句的四个组成部分
- 初始化部分(init_statement)
- 循环条件部分(test_exp)
- 循环体部分(body_statement)
- 迭代部分(alter_statement)

(4)循环结构1:for循环
语法格式
for (①初始化部分; ②循环条件部分; ④迭代部分){ ③循环体部分; }
执行过程:
①-②-③-④-②-③-④-②-③-④-.....-②
说明:
- ②循环条件部分为boolean类型表达式,当值为false时,退出循环
- ①初始化部分可以声明多个变量,但必须是同一个类型,用逗号分隔
- ④可以有多个变量更新,用逗号分隔
for 循环执行演示

应用举例
举例1
/** * @author: huxingxin * @date: 2022/11/18 15:40:58 * @description: * for循环结构的使用 * 一、循环结构的四个要素 * (1)初始化条件 * (2)循环条件 --> 是boolean类型 * (3)循环体 * (4)迭代条件 * * 二、for循环的结构 * for (①初始化部分; ②循环条件部分; ④迭代部分){ * ③循环体部分; * } * ①-②-③-④-②-③-④-②-③-④-.....-② */ public class ForLoop { public static void main(String[] args) { /*System.out.println("Hello Word !"); System.out.println("Hello Word !"); System.out.println("Hello Word !"); System.out.println("Hello Word !"); System.out.println("Hello Word !");*/ for(int i = 1; i <= 5; i++){ //i: 1 2 3 4 5 System.out.println("Hello Word !"); } } }
for循环的练习
练习1
/** * @author: huxingxin * @date: 2022/11/18 15:52:48 * @description: */ public class Test1 { public static void main(String[] args) { //第一题、输出结果是什么? int number = 1; for (System.out.print("a"); number <= 3; System.out.print("c"), number++){ System.out.print("b"); } //输出结果:abcbcbc System.out.println(); //第二题、遍历100以内的偶数,输出所有偶数的和 int sum = 0;//记录所有偶数的和,输出偶数的个数 int count = 0; for(int i = 1; i <= 100; i++){ if (i % 2 == 0){ sum += i; count++; System.out.print(i + ", "); } } System.out.println(); System.out.println("sum = " + sum); System.out.println("count = " + count); /* 编写程序从1循环到150,并在每行打印一个值,另外在每个3的倍数行 上打印出“foo”,在每个5的倍数行上打印“biz”,在每个7的倍数行上打印 输出“baz” */ for (int i = 1; i <= 150; i++){ System.out.print("i: " + i); if (i % 3 == 0){ System.out.print(" foo"); } if (i % 5 == 0){ System.out.print(" biz"); } if (i % 7 == 0){ System.out.print(" baz"); } System.out.println(); } } }
练习2
import java.util.Scanner; /** * @author: huxingxin * @date: 2022/11/18 21:32:15 * @description: */ public class Test2 { public static void main(String[] args) { /* 题目:输入两个正整数m和n,求其最大公约数和最小公倍数。 比如:12和20的最大公约数是4,最小公倍数是60。 说明:break关键字的使用 */ Scanner scanner = new Scanner(System.in); System.out.println("请输入两个正整数(m,n)"); System.out.print("m: "); int m = scanner.nextInt(); System.out.print("n: "); int n = scanner.nextInt(); //1、获最大公约数 //(1)获取两个数中的较小值 int min = m < n ? m : n; //(2)遍历 for (int i = min; i > 0; i--){ if ( m % i == 0 && n % i ==0){ System.out.println("最大公约数:" + i); break;//一旦在循环中执行到break,就跳出当前循环。 } } //1、获取最小公倍数 //(1)获取两个数中的较大值 int max = m > n ? m : n; //(2)遍历 for (int i = max; i <= m * n; i++){ if ( i % m == 0 && i % n == 0){ System.out.println("最小公倍数:" + i); break; } } } }
练习3
/** * @author: huxingxin * @date: 2022/11/18 21:55:36 * @description: */ public class Test4 { public static void main(String[] args) { /* 输出所有的水仙花数,所谓水仙花数是指一个3位数,其各个位上数字立方和等于其本身。 例如: 153 = 1*1*1 + 3*3*3 + 5*5*5 */ for (int i = 100; i <= 999; 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); } } } }
(5)循环结构2:while循环
语法格式
①初始化部分 while(②循环条件部分){ ③循环体部分; ④迭代部分; }
执行过程:
①-②-③-④-②-③-④-②-③-④-...-②
说明:
- 注意不要忘记声明④迭代部分。否则,循环将不能结束,变成死循环。
- for循环和while循环可以相互转换
应用举例
/** * @author: huxingxin * @date: 2022/11/19 12:44:32 * @description: * while循环结构的使用 * 一、循环结构的四个要素 * (1)初始化条件 * (2)循环条件 --> 是boolean类型 * (3)循环体 * (4)迭代条件 * * 二、while循环的结构 * ①初始化部分 * while(②循环条件部分){ * ③循环体部分; * ④迭代部分; * } * * ①-②-③-④-②-③-④-②-③-④-...-② * * 说明: * (1)写while循环千万小心不要丢了迭代条件,一旦丢了,就可能导致死循环。 * (2)我们写程序,要避免出现死循环 * (3) for循环和while循环是可以相互转换的。 * * 区别:for循环和while循环的初始化条件部分的作用范围不同。 * * 算法:有限性 * */ public class WhileLoop { public static void main(String[] args) { //遍历100以内所有的偶数 /* //丢失了迭代条件:死循环 int number = 2; while (number < 100){ if (number % 2 == 0){ System.out.println(number); } }*/ int number = 1; while (number <= 100){ if (number % 2 == 0){ System.out.println(number); } number++; } } }
(6)循环结构3:do-while循环
语法格式
①初始化部分; do{ ③循环体部分 ④迭代部分 }while(②循环条件部分);
执行过程:
①-③-④-②-③-④-②-③-④-...②
说明:
do-while循环至少执行一次循环体。
应用举例
/** * @author: huxingxin * @date: 2022/11/19 13:01:24 * @description: * do-while循环结构的使用 * 一、循环结构的四个要素 * (1)初始化条件 * (2)循环条件 --> 是boolean类型 * (3)循环体 * (4)迭代条件 * * 二、do-while循环的结构 * ①初始化部分; * do{ * ③循环体部分 * ④迭代部分 * }while(②循环条件部分); * * ①-②-③-④-②-③-④-②-③-④-...-② * * 说明: * 1、do-while循环至少会执行一次循环体 * 2、开发中使用for和while更多一下。do-while较少 */ public class DoWhileLoo { public static void main(String[] args) { //循环100以内的偶数,并计算所有偶数的和及偶数的个数 int number = 1; int sum = 0;//记录总和 int count = 0;//记录个数 do { if (number % 2 == 0){ System.out.println(number); sum += number; count++; } number++; }while (number <= 100); System.out.println("所有偶数的和:" + sum); System.out.println("偶数的个数:" + count); } }
(7)循环语句综合例题
最简单“无限” 循环格式:while(true) , for(;;),
无限循环存在的原因是并不知道循环多少次,需要根据循环体内部某些条件,来控制循环的结束。
import java.util.Scanner; /** * @author: huxingxin * @date: 2022/11/19 13:39:54 * @description: where(true)结构的使用 * * 说明: * 1、不在循环条件部分限制次数的结构:for(;;) 或 while(true) * 2、结束循环有几种方式? * (1)循环条件部分,返回false * (2)在循环体中,执行break */ public class PositiveNegative { public static void main(String[] args) { //从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序 //最简单“无限” 循环格式:while(true) , for(;;),无限循环存在的原因是并不知道循环多少次,需要根据循环体内部某些条件,来控制循环的结束。 Scanner scanner = new Scanner(System.in); int positiveNum = 0;//记录正数个数 int negativeNum = 0;//记录负数个数 for (;;)/*while (true)*/{ System.out.print("请输入整数:"); int number = scanner.nextInt(); if (number > 0){ positiveNum++; }else if (number < 0){ negativeNum++; }else { break; } } System.out.println("正数 " + positiveNum + " 个,负数 " + negativeNum + " 个"); } }
(8)嵌套循环(多重循环)
- 将一个循环放在另一个循环体内,就形成了嵌套循环。其中,
for, while, do…while
均可以作为外层循环或内层循环。 - 实质上,嵌套循环就是把内层循环当成外层循环的循环体。当只有内层循环的循环条件为false时,才会完全跳出内层循环,才可结束外层的当次循环,开始下一次的循环。
- 设外层循环次数为m次,内层为n次,则内层循环体实际上需要执行
m*n
次。
嵌套循环的使用
/** * @author: huxingxin * @date: 2022/11/20 23:52:37 * @description: * 1、嵌套循环:将一个循环结构A声明在另一个循环结构B的循环体中,就构成了嵌套循环。 * 2、 * 外层循环:循环结构B * 内层循环:循环结构A * * 3、 * (1)内存循环结构遍历一遍,只相当于外层循环循环体执行了一次。 * (2)假设外层循环需要执行m次,外层循环体需要执行n次,此时内层循环的循环体执行了 m*n 次。 * * 4、外层循环控制行数,内存循环控制列数。 */ public class NestedLoop { public static void main(String[] args) { //输出 ****** for (int i = 1; i <= 6; i++){ System.out.print("*"); } System.out.println("\n------------------------"); /* 输出 ****** ****** ****** ****** ****** */ for (int i = 1; i <= 5; i++){ for (int j = 1; j <= 6; j++){ System.out.print("*"); } System.out.println(); } System.out.println("\n------------------------"); /* 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(); } System.out.println("\n------------------------"); /* i(行号) j(*的个数) 输出 ***** 1 5 **** 2 4 *** 3 3 ** 2 2 * 1 1 */ for (int i = 1; i <= 5; i++){ //控制行数 for (int j = 1; j <= 6 - i; j++){ //控制列数 System.out.print("*"); } System.out.println(); } System.out.println("\n------------------------"); /* i(行号) j(*的个数) 输出 * 1 1 ** 2 2 *** 3 3 **** 4 4 ***** 5 5 **** 6 4 *** 7 3 ** 8 2 * 9 1 */ for (int i = 1; i <= 9; i++){ //控制行数 if (i < 6){ for (int j = 1; j <= i; j++){ //控制列数 System.out.print("*"); } }else { for (int j = 1; j <= 10 -i ; j++){ //控制列数 System.out.print("*"); } } System.out.println(); } System.out.println("\n------------------------"); /* i(行号) j(*的个数) k(左边空格的个数) 输出 * 1 1 4 * * 2 2 3 * * * 3 3 2 * * * * 4 4 1 * * * * * 5 5 0 * * * * 6 4 4 * * * 7 3 3 * * 8 2 2 * 9 1 1 */ // for (int i = 1; i <= 9; i++){ // if (i < 6){ // for (int k = 1; k <= 5 - i; k++){ // System.out.print(" "); // } // for (int j = 1; j <= i; j++){ // System.out.print("* "); // } // }else { // for (int k = 1; k <= i - 5; k++){ // System.out.print(" "); // } // for (int j = 1; j <= 10 - i; j++){ // System.out.print("* "); // } // } // System.out.println(); // } for (int i = 1; i <= 5; i++){ for (int k = 1; k <= 5 - i; k++){ System.out.print(" "); } for (int j = 1; j <= i; j++){ System.out.print("* "); } System.out.println(); } for (int i = 1; i <= 4; i++){ for (int k = 1; k <= i; k++){ System.out.print(" "); } for (int j = 1; j <= 5 - i; j++){ System.out.print("* "); } System.out.println(); } } }
嵌套循环的练习
/** * @author: huxingxin * @date: 2022/11/21 9:27:27 * @description: */ public class Test1 { public static void main(String[] args) { //1、九九乘法表 for (int i = 1; i <= 9; i++){ for (int j = 1; j <= i; j++){ System.out.print(j + " x " + i + " = " + j * i); System.out.print("\t"); } System.out.println(); } //1、100以内所有质数 //质数(素数)是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。 // for (int i = 2; i <= 100; i++){ //遍历100以内的自然数 // for (int j = 2; j <= i; j++){ // if (i != j && i % j == 0){ // break; // }else if (i == j){ //表示一直被除尽 都没有其他的因数 // System.out.print(i + ", "); // } // } // } //逻辑优化 // System.out.println(); // boolean isPrimeNumbers = true; //写在外面更节省内存 // for (int i = 2; i <= 100; i++){ //遍历100以内的自然数 // for (int j = 2; j < i; j++){ // if (i % j == 0) { //如果有其它的因数 // isPrimeNumbers = false; // } // } // if (isPrimeNumbers){ // System.out.print(i + ", "); // } // isPrimeNumbers = true; //重置isPrimeNumbers // } //效率优化 System.out.println(); boolean isPrimeNumbers = true; //写在外面更节省内存 long startTime = System.currentTimeMillis(); for (int i = 2; i <= 100000; i++){ //遍历100以内的自然数 //优化二:开方 Math.sqrt() 、对本身是质数也有效 for (int j = 2; j < Math.sqrt(i); j++){ if (i % j == 0) { //如果有其它的因数 isPrimeNumbers = false; break; //优化一: 只对本身非质数的自然数 () } } if (isPrimeNumbers){ System.out.print(i + ", "); } isPrimeNumbers = true; //重置isPrimeNumbers } long endTime = System.currentTimeMillis(); System.out.println(); System.out.println(endTime - startTime); //没优化 6601毫秒 优化一 667毫秒 优化二 133毫秒 一起优化 32毫秒 } }
(9)特殊流程控制语句
特殊流程控制语句说明
break
只能用于switch语句
和循环语句
中。continue
只能用于循环语句
中。- 二者功能类似,但continue是终止本次循环,break是终止本层循环。
- break、continue之后不能有其他的语句,因为程序永远不会执行其后的语句。
- 标号语句必须紧接在循环的头部。标号语句不能用在非循环语句的前面。
- 很多语言都有goto语句,goto语句可以随意将控制转移到程序中的任意一条语句上,然后执行它。但使程序容易出错。Java中的break和continue是不同于goto的。
break 语句
-
break语句用于终止某个语句块的执行
-
{ ... break; ... }
-
-
break语句出现在多层嵌套的语句块中时,可以通过标签指明要终止的是哪一层语句块
-
label1: { ... label2: { ... label3: { ... break label2; ... } } }
-
continue 语句
- continue只能使用在循环结构中
- continue语句用于跳过其所在循环语句块的一次执行,继续下一次循环
- continue语句出现在多层嵌套的循环语句体中时,可以通过标签指明要跳过的是哪一层循环
break和continue的使用
/** * @author: huxingxin * @date: 2022/11/21 20:47:38 * @description: * * break和continue关键字的使用 * 使用范围 循环中使用的作用(不同点) (相同点) * break switch-case * 循环结构中 结束当前循环 * *continue 循环结构中 结束当次循环 关键字后面不能声明语句 */ public class BreakAndContinue { public static void main(String[] args) { for (int i = 1; i <= 10; i++){ if (i == 5){ break; //break:1, 2, 3, 4, 到5开始退出整个循环 // continue; //continue:1, 2, 3, 4, 6, 7, 8, 9, 10, 只退出i==5的那次循环 } System.out.print(i + ", "); } System.out.println("\n-----------------------"); //label 自定义标识 也可以是a b 符合标识符的命名规则即可 label: for (int i = 1; i <= 4; i++){ for (int j = 1; j <= 10; j++){ if (j == 5){ // break; //默认跳出包裹此关键字最近的一次循环 // continue;//也是默认作用于最近的循环结构 // break label; //结束指定标识的循环结构 continue label; //结束指标识的一层循环结构当此循环 } System.out.print(j + ", "); } System.out.println(); } } }
输出质数的方式二
/** * @author: huxingxin * @date: 2022/11/21 21:41:47 * @description: */ public class Test2 { public static void main(String[] args) { //1、100以内所有质数 //质数(素数)是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。 long startTime = System.currentTimeMillis(); label: for (int i = 2; i <= 100000; i++){ //遍历100以内的自然数 for (int j = 2; j < Math.sqrt(i); j++){ if (i % j == 0) { //如果有其它的因数 continue label; } } System.out.print(i + ", "); } long endTime = System.currentTimeMillis(); System.out.println(); System.out.println(endTime - startTime); } }
return语句
- 并非专门用于结束循环的,它的功能是结束一个方法。当一个方法执行到一个return语句时,这个方法将被结束。
- 与break和continue不同的是,return直接结束整个方法,不管这个return处于多少层循环之内
本文作者:huxingxin
本文链接:https://www.cnblogs.com/huxingxin/articles/16903836.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)