程序逻辑控制
- BIT-4 逻辑控制
- 1. 概述
- 2. 顺序结构
- 3. 分支结构
- 3.1 if语句
- 3.1.1 语法格式1
- 3.1.2 语法格式2
- 3.1.3 语法格式3
- 3.2 switch 语句
- 4. 循环结构
- 4.1 while 循环
- 4.2 break
- 4.3 continue
- 4.4 for循环
- 4.5 do while 循环
- 5. 输入输出
- 5.1 输出到控制台
- 4.2 从键盘输入
- 5. 猜数字游戏
BIT-4 逻辑控制
【本节目标】
-
Java中程序的逻辑控制语句
-
Java中的输入输出方式
-
完成猜数字游戏
1. 概述
我的曾经:
早上8:00起床—>洗漱—>吃早饭—>上课—>吃午饭—>上课—>运动—>吃完饭—>玩手机—>睡觉
每天的生活貌似都是这么规律,顺序的做着每件事,前途一片渺茫~~~
直到有一天:
我幡然醒悟,不好好学习可能要卖红薯,奋发图强可能离梦想会更近,于是我选择努力学习,从此:
早上6:00起床—>看书敲代码—>上课+看编程书籍—>吃午饭—>刷题—>上课+看书—>吃晚饭—>总结—>看科技新闻—>睡觉
就这样日复一日的努力着,感觉每天都很充实,生活看到了希望~~~
再后来:
秋招来了,我用自己所学,一次次刷新着手中offffer的记录,那一刻,我被自己感动了
~~~
其实程序和人生是一样:顺序中夹杂着循环,伴随一次次选择不断成长。
2. 顺序结构
顺序结构比较简单,按照代码书写的顺序一行一行执行。
代码示例
public static void main(String[] args) {System.out.println(1);System.out.println(2);System.out.println(456);
}
//------------
//编译器运行结果为
//1
//2
//456
如果调整代码的书写顺序, 则执行顺序也发生变化
public static void main(String[] args) {System.out.println(1);System.out.println(456);System.out.println(2);
}
//----------
//编译器运行结果为
//1
//456
//2
3. 分支结构
3.1 if语句
3.1.1 语法格式1
if(布尔表达式){// 语句
}
如果布尔表达式结果为true,执行if中的语句,否则不执行。
虽然在执行语句只有一行的时候,可以不加大括号,但是为了提高可读性,尽量要加上大括号。
代码示例
public static void main(String[] args) {int score = 90;if(score >= 90){System.out.println("优秀");}
}
//-------------
//编译器运行结果为
//优秀
3.1.2 语法格式2
if(布尔表达式){// 语句1
}else{// 语句2
}
如果布尔表达式结果为true,则执行if中语句,否则执行else中语句。
代码示例
public static void main(String[] args) {int a = 10;if(a == 10){System.out.println("a == 10");}else{System.out.println("a != 10");}
//----------
//编译器运行结果为
//a == 10
如果不加else
public static void main(String[] args) {int a = 10;if(a == 10){System.out.println("a == 10");}else{System.out.println("a != 10");}int b = 10;if(b == 10){System.out.println("b == 10");}System.out.println("b != 10");
}
//--------------
//编译器运行结果为
//a == 10
//b == 10
//b != 10
3.1.3 语法格式3
if(布尔表达式1){// 语句1
}else if(布尔表达式2){// 语句2
}else{// 语句3
}
表达式1成立,执行语句1,否则表达式2成立,执行语句2,否则执行语句3
比如:考虑到学生自尊,不公开分数排名,因此:
- 分数在 [90, 100] 之间的,为优秀
- 分数在 [80, 90) 之前的,为良好
- 分数在 [70, 80) 之间的,为中等
- 分数在 [60, 70) 之间的,为及格
- 分数在 [ 0, 60) 之间的,为不及格
- 错误数据
按照上述办法通知学生成绩。
public static void main(String[] args) {int score = 0;if(score >=90 && score <=100){System.out.println("优秀");}else if(score >= 80 && score < 90){System.out.println("良好");}else if(score >= 70 && score <80){System.out.println("中等");}else if(score >= 60 && score < 70){System.out.println("及格");}else if(score >= 50 && score <60) {System.out.println("不及格");}else{System.out.println("错误数据");}
}
【练习】
- 判断一个数字是奇数还是偶数
public static void main(String[] args) {int num = 20;if(num % 2 == 0){System.out.println("偶数");}else{System.out.println("奇数");}
}
//------------
//编译器运行结果为
//偶数
- 判断一个数字是正数,负数,还是零
public static void main(String[] args) {int a = 10;if(a > 0) {System.out.println("正数");}else if(a < 0) {System.out.println("负数");}else {System.out.println("零");}
}
//-------------
//编译器运行结果为
//正数
这里有些编程习惯
补充
黄色的这种属于警告。
- 判断一个年份是否为闰年
普通闰年:公历年份是4的倍数,且不是100的倍数的,为闰年。
世纪闰年:公历年份是整百数的,必须是400的倍数才是闰年。
闰年的判断方法: 被4整除且不被100整除,或者被400整除。
代码示例
public static void main(String[] args) {int year = 2000;if(year % 100 == 0){//世纪闰年if((year % 400) == 0){System.out.println(year + "是闰年");}else{System.out.println(year + "不是闰年");}}else{//普通闰年if(year % 4 == 0){System.out.println(year + "是闰年");}else{System.out.println(year + "不是闰年");}}
}
//----------------
//编译器运行结果为
//2000是闰年
代码简化
public static void main(String[] args) {int num = 2020;if(num % 100 == 0 && num % 400 == 0||num % 100 != 0 && num % 4 == 0){System.out.println(num + "是闰年" );}else{System.out.println(num + "不是闰年");}
}
再次简化
public static void main(String[] args) {int num = 2020;if( num % 400 == 0 || num % 100 != 0 && num % 4 == 0){System.out.println(num + "是闰年" );}else{System.out.println(num + "不是闰年");}
}
【注意事项】
- 代码风格
// 风格1-----> 推荐
int x = 10;
if (x == 10) {// 语句1
} else {// 语句2
}// 风格2
int x = 10;
if (x == 10)
{// 语句1
}
else
{// 语句2
}
虽然两种方式都是合法的, 但是 Java 中更推荐使用风格1, { 放在 if / else 同一行. 代码跟紧凑。
- 分号问题
int x = 20;
if (x == 10);
{System.out.println("hehe");
}
// 运行结果
hehe
此处多写了一个 分号, 导致分号成为了 if 语句的语句体, 而 { } 中的代码已经成为了和一个 if 无关的代码块.
- 悬垂 else 问题
int x = 10;
int y = 10;
if (x == 10) if (y == 10)System.out.println("aaa");
elseSystem.out.println("bbb");
if / else 语句中可以不加 大括号 . 但是也可以写语句(只能写一条语句). 此时 else 是和最接近的 if 匹配.
但是实际开发中我们 不建议 这么写. 最好加上大括号.
补充
有一个名词叫做背调(背景调查)
所以找工作的时候,会对自己之前的公司进行询问自己的个人情况,以及工作态度等等。。
所以我们应该有职业道德精神。
3.2 switch 语句
switch语句和C语言中没有区别。
基本语法
switch(表达式){case 常量值1:{语句1;[break;]}case 常量值2:{语句2;[break;]}...default:{内容都不满足时执行语句;[break;]}
}
执行流程:
-
先计算表达式的值
-
和case依次比较,一旦有响应的匹配就执行该项下的语句,直到遇到break时结束
-
当表达式的值没有与所列项匹配时,执行default
代码示例:
根据 day 的值输出星期
public static void main(String[] args) {int day = 7;switch (day){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;default:System.out.println("输入错误");break;}
}
//-----------------
//编译器运行结果为
//星期天
面试题
不能做switch
参数的数据类型是什么?
long float double boolean
【注意事项】
-
多个case后的常量值不可以重复
-
switch的括号内只能是以下类型的表达式:
○ 基本类型:byte、char、short、int,注意不能是long类型
○ 引用类型:String常量串、枚举类型
double num = 1.0;
switch(num) {case 1.0:System.out.println("hehe");break;case 2.0:System.out.println("haha");break; }
// 编译出错
Test.java:4: 错误: 不兼容的类型: 从double转换到int可能会有损失switch(num) {^ 1 个错误
- break 不要遗漏, 否则会失去 “多分支选择” 的效果
int day = 1;
switch(day) {case 1:System.out.println("星期一");// break;case 2:System.out.println("星期二");break; }
// 运行结果
星期一
星期二
- switch 不能表达复杂的条件
// 例如: 如果 num 的值在 10 到 20 之间, 就打印 hehe
// 这样的代码使用 if 很容易表达, 但是使用 switch 就无法表示.
if (num > 10 && num < 20) {System.out.println("hehe");
}
- switch 虽然支持嵌套, 但是很丑,一般不推荐~
int x = 1;
int y = 1;
switch(x) {case 1:switch(y) {case 1:System.out.println("hehe");break;}
}
综上, 我们发现, switch 的使用局限性是比较大的。
4. 循环结构
4.1 while 循环
基本语法格式
while(布尔表达式){循环语句; }
布尔表达式为 true, 则执行循环语句; 否则结束循环
代码示例1: 打印 1 - 10 的数字
public static void main(String[] args) {int a = 1;while (a <= 10) {System.out.println(a);a++;}
}
//-----------
//编译器运行结果为
//1
//2
//3
//4
//5
//6
//7
//8
//9
//10
代码示例2: 计算 1 - 100 的和
public static void main(String[] args) {int a = 1;int sum = 0;while (a <= 100) {sum += a;a++;}System.out.println("1-100和是" + sum);System.out.println("===========");a = 1;sum = 0;while(a <= 100) {sum += a;a += 2;}System.out.println("1-100奇数和为" + sum);
}
//-----------
//编译器运行结果为
//1-100和是5050
//===========
//1-100奇数和为2500
代码示例3: 计算 5 的阶乘
public static void main(String[] args) {int a = 1;int fac = 1;while(a <= 5) {fac *= a;a++;}System.out.println(fac);
}
//------------
//编译器运行结果为
//120
代码示例4: 计算 1! + 2! + 3! + 4! + 5!
public static void main(String[] args) {int i = 1;int sum = 0;while(i <= 5) {int a = 1;int fac = 1;while(a <= i) {fac *= a;a++;}sum += fac;i++;}System.out.println(sum);}
//------------
//编译器运行结果为
//153
进行简化
public static void main(String[] args) {int i = 1;int fac = 1;int sum = 0;while (i <= 5) {fac *= i;sum += fac;i++;}System.out.println(sum);
}
//------------
//编译器运行结果为
//153
注意事项
-
和 if 类似, while 下面的语句可以不写 { } , 但是不写的时候只能支持一条语句. 建议还是加上 { }
-
和 if 类似, while 后面的 { 建议和 while 写在同一行.
-
和 if 类似, while 后面不要多写 分号, 否则可能导致循环不能正确执行.
补充
如果想要在Java当中写出死循环,代码如下
public static void main(String[] args) {int a = 10;while (true) {System.out.println(a);}
}
//死循环打印10
调试
4.2 break
break 的功能是让循环提前结束
public static void main(String[] args) {int a = 1;while (a <= 3) {System.out.println(a);if(a == 2){break;}a++;}
}
//----------
//编译器运行结果为
//1
//2
执行到 break 就会让循环结束
4.3 continue
continue 的功能是跳过这次循环, 立即进入下次循环的判断部分
代码示例:
public static void main(String[] args) {int a = 1;while (a <= 3) {System.out.println(a);if(a == 2){continue;}a++;}
}
//-------------
//编译器运行结果为
//1
//2
//2
//...一直循环打印2
//2
代码示例: 找到 100 - 200 中所有 3 的倍数 要求:使用break 或者continue 当中的一个。
public static void main(String[] args) {int a = 1;while (a <= 100) {if(a % 3 == 0 && a % 5 == 0){System.out.println(a);}else{a += 1;continue;}a += 3;}
}
//-------------
//编译器运行结果为
//15
//30
//45
//60
//75
//90
4.4 for循环
【基本语法】
for(表达式①;布尔表达式②;表达式③){表达式④;
}
- 表达式1: 用于初始化循环变量初始值设置,在循环最开始时执行,且只执行一次
- 布尔表达式2: 循环条件,满则循环继续,否则循环结束
- 表达式3: 循环变量更新方式
【执行过程】
①②③④—>②③④—>②③④—>②③④—>②③④—>②③④—>…—>②为false,循环结束。
【代码示例】
- 打印 1 - 10 的数字
public static void main(String[] args) {//fori 回车for (int i = 1; i <= 10; i++) {System.out.println(i);}
}
//-------------
//编译器运行结果为
//1
//2
//3
//4
//5
//6
//7
//8
//9
//10
- 计算 1 - 100 的和
int sum = 0;
for (int i = 1; i <= 100; i++) {sum += i; }
System.out.println("sum = " + sum);
// 执行结果
5050
- 计算 5 的阶乘
int result = 1;
for (int i = 1; i <= 5; i++) {result *= i; }
System.out.println("result = " + result);
- 计算1!+ 2!+ 3!+ 4!+ 5!的和
public static void main(String[] args) {int fac = 1;int sum = 0;for (int i = 1; i <= 5 ; i++) {fac *= i;sum += fac;}System.out.println(sum);
}
//--------------
//编译器运行结果为
//153
for循环的死循环写法
方法一
public static void main(String[] args) {for (int i = 0; true ; i++) {System.out.println(1);}
}
方法二
public static void main(String[] args) {for (int i = 0; ; i++) {System.out.println(1);}
}
//当for循环中的判断部分为空时,默认为true
【注意事项】 (和while循环类似)
-
和 if 类似, for 下面的语句可以不写 { } , 但是不写的时候只能支持一条语句. 建议还是加上 { }
-
和 if 类似, for 后面的 { 建议和 while 写在同一行.
-
和 if 类似, for 后面不要多写 分号, 否则可能导致循环不能正确执行.
-
和while循环一样,结束单趟循环用continue,结束整个循环用break
4.5 do while 循环
【基本语法】
do{循环语句;
} while (循环条件);
先执行循环语句, 再判定循环条件,循环条件成立则继续执行,否则循环结束。
例如:打印 1 - 10
public static void main(String[] args) {int a = 1;do {System.out.println(a);a++;} while (a <= 10);
}
【注意事项】
-
do while 循环最后的分号不要忘记
-
一般 do while 很少用到, 更推荐使用 for 和 while.
5. 输入输出
5.1 输出到控制台
基本语法
System.out.println(msg); // 输出一个字符串, 带换行
System.out.print(msg); // 输出一个字符串, 不带换行
System.out.printf(format, msg); // 格式化输出
println
和print
和printf
public static void main(String[] args) {System.out.println("输出切换行");System.out.print("输出且不换行");System.out.printf("%s\n","格式化输出!和C语言一样!");
}
//-------------
//编译器运行结果为
//输出切换行
//输出且不换行格式化输出!和C语言一样!
一般情况下,我们用前两个多一点。
格式化字符串
4.2 从键盘输入
在Java当中,我们会用到Java官方写好的一个工具——类
使用 Scanner 读取字符串/整数/浮点数
Scanner
是一个类
如果读入一个整数
代码示例1
public static void main(String[] args) {Scanner scan = new Scanner(System.in);int n = scan.nextInt();System.out.println(n);
}
代码示例2
public static void main(String[] args) {Scanner scan = new Scanner(System.in);System.out.println("请输入你的姓名");String str = scan.nextLine();System.out.println(str);System.out.println("请输入你的年龄");int n = scan.nextInt();System.out.println(n);System.out.println("请输入你的工资");float wage = scan.nextFloat();System.out.println(wage);scan.close();}
//------------
//编译器运行结果为
//请输入你的姓名
//meng dehong
//meng dehong
//请输入你的年龄
//20
//20
//请输入你的工资
//0.00
//0.0
next
和nextLine
的区别
public static void main(String[] args) {Scanner scan = new Scanner(System.in);String name = scan.next();System.out.println(name);String name2 = scan.next();System.out.println(name2);// String str2 = scan.next();// System.out.println(str2);// next相较于nextLine有一个很大的缺点,遇到空格,停止扫描
}
//---------------
//编译器运行结果为
//meng dehong
//meng
//dehong
next
相较于nextLine
有一个很大的缺点,遇到空格后停止扫描。
当年龄和姓名代码交换位置进行输入输出时
代码示例
public static void main(String[] args) {Scanner scan = new Scanner(System.in);System.out.println("请输入年龄");int age = scan.nextInt();System.out.println(age);System.out.println("请输入姓名");String name = scan.nextLine();System.out.println(name);}
//-------------
//编译器运行结果为
//请输入年龄
//123
//123
//请输入姓名
因为输入完年龄后进行回车,回车会被读取到字符串name
中。
解决办法
将缓冲区中的回车提前进行读取
public static void main(String[] args) {Scanner scan = new Scanner(System.in);System.out.println("请输入年龄");int age = scan.nextInt();System.out.println(age);scan.nextLine();//清空缓冲区的回车System.out.println("请输入姓名");String name = scan.nextLine();System.out.println(name);}
循环输入和输出
public static void main(String[] args) {Scanner scan = new Scanner(System.in);while (scan.hasNextInt()) {int n = scan.nextInt();System.out.println("n = "+n);}
}
结束通过ctrl+d
5. 猜数字游戏
游戏规则:
系统自动生成一个随机整数(1-100), 然后由用户输入一个猜测的数字. 如果输入的数字比该随机数小, 提示 “低了”, 如果输入的数字比该随机数大, 提示 “高了” , 如果输入的数字和随机数相等, 则提示 “猜对了” .
生成随机数字的方法
public static void main(String[] args) {Scanner scan = new Scanner(System.in);Random random = new Random();int randNum = random.nextInt(100); //[0,100)System.out.println(randNum);
}
猜数字游戏
public static void main(String[] args) {Scanner scan = new Scanner(System.in);//生成随机数字Random random = new Random();int randNum = random.nextInt(100); //[0,100)System.out.println(randNum);//猜数字while (true) {System.out.println("请输入你要猜的数字");int scanNum = scan.nextInt();if (scanNum > randNum) {System.out.println("猜大了");}else if (scanNum < randNum) {System.out.println("猜小了");}else {System.out.println("猜对了");break;}}
}
补充
如何生成100-200的数字
int randNum = random.nextInt(100) + 100; //[0,100)
这就是关于程序逻辑控制的所有内容,比较简单,小伙伴们一定都能够掌握。我们下节再见。