程序控制结构
在程序中,程序运行的流程控制决定程序是如何执行的,是我们必须掌握的,主要有三大流程控制语句:
-
顺序控制
-
分支控制
-
循环控制
顺序控制
定义:程序从上到下逐行地执行,中间没有任何的判断和跳转。
-
顺序控制举例和注意事项
Java中定义成员变量时采用合法的前向引用。如:public class Test{ public static void main(String[] args){ int num1 = 12; int num2 = num1 + 1; } }
错误形式,如下:
public class Test{ public static void main(String[] args){ int num2 = num1 + 1;//错误 int num1 = 12; } }
分支控制if-else
让程序有选择的执行,分支控制有三种
- 单分支 if
- 双分支 if-else
- 多分支 if-else if -....-else
单分支
- 基本语法
if(条件表达式){
执行代码块;(可以有多条语句)
} - 说明:当条件表达式为true时,就会执行{}里的代码;如果结果为false,就不执行。特别说明,如果{}中只有一条语句,则可以不用{}。(建议写上{})
//if的快速入门
import java.util.Scanner;
public class if01{
public static void main(String[] args) {
//接受输入的年龄
//定义一个Scanner对象
Scanner myScanner = new Scanner(System.in);
System.out.println("请输入年龄:");
//将年龄保存到变量中
int age = myScanner.nextInt();
//使用if判断,输出对应的内容
if (age >= 18) {
System.out.println("你的年龄已经18了,作为一个成年人,你要对自己的行为负责。");
}
System.out.println("程序继续......");
}
}
双分支
- 基本语法
if(条件表达式){
执行代码块1;
}else{
执行代码块2;
} - 说明:当条件表达式为true时,就会执行代码块1;如果结果为false,就执行代码块2。
//if-else的快速入门
import java.util.Scanner;
public class if02{
public static void main(String[] args) {
//接受输入的年龄
//定义一个Scanner对象
Scanner myScanner = new Scanner(System.in);
System.out.println("请输入年龄:");
//将年龄保存到变量中
int age = myScanner.nextInt();
//使用if判断,输出对应的内容
if (age >= 18) {
System.out.println("你的年龄已经18了,作为一个成年人,你要对自己的行为负责。");
}else{
System.out.println("你的年龄未满18,是未成年人,要好好学习");
}
System.out.println("程序继续......");
}
}
多分支
-基本语法
if(条件表达式1){
执行代码块1;
}else if(条件表达式2){
执行代码块2;
}else if(条件表达式3){
...
}else{
执行代码块n;
}
- <label class="task-list-item-label" for="task-item-3447998"> 注:多分支可以没有else,如果所有的条件表达式都不成立,则一个执行入口都没有。</label>
- <label class="task-list-item-label" for="task-item-9051025"> 如果有else,所有的条件表达式都不成立,则默认执行else代码块。</label>
//多分支
import java.util.Scanner;
public class If03{
public static void main(String[] args) {
/*
输入芝麻信用分:
如果: 信用分为 100 分时,输出 信用极好;
信用分为(80,99]时,输出 信用优秀;
信用分为[60,80]时,输出 信用一般;
其它情况 ,输出 信用 不及格
请从键盘输入芝麻信用分,并加以判断
假定信用分数为 int
*/
Scanner myScanner = new Scanner(System.in);
//接受芝麻信用分
System.out.println("请输入信用分(1-100):");
int grade = myScanner.nextInt();
if (grade >= 1 && grade <= 100) {
if(grade == 100){
System.out.println("信用极好");
}else if (grade > 80 && grade <= 99) {
System.out.println("信用优秀");
}else if (grade > 60 && grade <= 80) {
System.out.println("信用一般");
}else{
System.out.println("信用不及格");
}
}else{
System.out.println("信用分需在1-100,请重新输入");
}
}
}
嵌套分支
在一个分支结构中又完整的嵌套了另一个完整的分支结构,里面的分支的结构称为内层分支外面的分支结构称为外层分支。
if () {
if(){
}else if () {
}else{
}
}else{
}
import java.util.Scanner;
public class NestedIf {
//编写一个main方法
public static void main(String[] args) {
/*
参加歌手比赛,如果初赛成绩大于8.0进入决赛,
否则提示淘汰。并且根据性别提示进入男子组或女子组。
, 输入成绩和性别,进行判断和输出信息。
[NestedIf.java]
提示: double score; char gender;
接收字符: char gender = scanner.next().charAt(0)
*/
//思路分析
//1. 创建Scanner对象,接收用户输入
//2. 接收 成绩保存到 double score
//3. 使用 if-else 判断 如果初赛成绩大于8.0进入决赛,否则提示淘汰
//4. 如果进入到 决赛,再接收 char gender, 使用 if-else 输出信息
//代码实现 => 思路 --> java代码
Scanner myScanner = new Scanner(System.in);
System.out.println("请输入该歌手的成绩");
double score = myScanner.nextDouble();
if( score > 8.0 ) {
System.out.println("请输入性别");
char gender = myScanner.next().charAt(0);
if( gender == '男' ) {
System.out.println("进入男子组");
} else if(gender == '女') {
System.out.println("进入女子组");
} else {
System.out.println("你的性别有误,不能参加决赛~");
}
} else {
System.out.println("sorry ,你被淘汰了~");
}
}
}
Swith分支结构
swith(表达式){
case 常量1:
语句块1;
break;
case 常量2:
语句块2;
break;
...
case 常量n:
语句块n;
break;
default:
default语句块;
break;
}
- switch关键字,表示switch分支。
- 表达式对应一个值。
- case 常量1:当表达式的值等于常量1,就执行语句块1
- break:表示退出switch
- 如果和case常量1匹配,就执行语句块1,如果没有匹配,就继续匹配 case 常量2
- 如果一个都没有匹配上,执行default
import java.util.Scanner;
public class Switch01{
public static void main(String[] args) {
/*
请编写一个程序,该程序可以接收一个字符,
比如:a,b,c,d,e,f,g
a 表示星期一,b 表示星期二 …
根据用户的输入显示相应的信息.要求使用 switch 语句完成
思路分析
1. 接收一个字符 , 创建 Scanner 对象
2. 使用 switch 来完成匹配,并输出对应信息
*/
Scanner myScanner = new Scanner(System.in);
System.out.println("请输入一个字符(a-g)");
char c1 = myScanner.next().charAt(0);
//在java中,只要有值返回,就是一个表达式
switch(c1) {
case 'a':
System.out.println("今天星期一");
break;
case 'b':
System.out.println("今天星期二");
break;
case 'c':
System.out.println("今天星期三");
break;
case 'd':
System.out.println("今天星期四");
break;
case 'e':
System.out.println("今天星期五");
break;
case 'f':
System.out.println("今天星期六");
break;
case 'g':
System.out.println("今天星期日");
break;
default:
System.out.println("你输入的字符不正确,没有匹配的");
}
System.out.println("退出了switch,继续执行程序");
}
}
-
Switch的注意事项
- 表达式数据类型,应和case后的常量类型一致,或者是可以自动转成可以相互比较的类型,比如输入的是字符,而常量是int。
- switch(表达式)中表达式的返回值必须是:(byte,short,int,char,enum,String).
- case子句中的值必须是常量,而不能是变量。
- default子句是可选的,当没有匹配的case时,执行default。
- break语句用来在执行完一个case分支后使程序跳出switch语句块;如果没有写break,程序会顺序执行到switch结尾。
-
switch和if的比较
- 如果判断的具体数值不多,而且符合 byte、 short 、int、 char, enum[枚举], String 这 6 种类型。虽然两个语句都可 以使用,建议使用 swtich 语句。
- 其他情况:对区间判断,对结果为 boolean 类型判断,使用 if,if 的使用范围更广。
for循环控制
- 基本语法
for(循环变量的初始化;循环条件;循环变量迭代){
循环操作(可以多条语句);
} - 补充说明
- for关键字,表示循环控制。
- for有四要素:循环变量初始化、循环条件、循环变量迭代、循环操作。
- 循环操作,这里可以有多条语句,也就是我们要循环执行的代码。
- 如果循环操作只有一条语句,{}可以省略,但不建议省略。
- 使用细节
- 循环条件是返回一个布尔值的表达式。
- for(;循环判断条件;)中的初始化和变量迭代可以写到其它地方,但是两边的分号不能省略。
- 循环初始值可以有多条初始化语句,但要求类型一样,并且中间用逗号隔开,循环变量迭代也可以有多条变量迭代语句,中间用逗号隔开。
public class ForExercise{
public static void main(String[] args) {
/*
打印1~100之间所有是9的倍数的整数,统计个数及总和。[化繁为简,先死后活]
1.化繁为简:即将复杂的需求,拆解成简单的需求,逐步完成
1.先死后活:先考虑固定的值,然后转成可以灵活变化的值
*/
//count用来统计个数
int count = 0;
//total用来统计总和
int total = 0;
for (int i = 1;i <= 100 ;i++ ) {
// 对9的余数为零,就是9的倍数的整数
if (i % 9 == 0) {
//将该数记录一个个数
count++;
// 将该数加入总和
total += i;
// 打印输出该整数
System.out.println(i);
}
}
// 打印输出总个数和总和
System.out.println("总个数为:" + count);
System.out.println("总和为:" + total);
}
}
while循环控制
- 基本语法
循环变量初始化;
while(循环条件){
循环体(语句);
循环变量迭代;
} - 说明
while循环也有四要素,只是四要素放的位置不一样。
public class While01{
public static void main(String[] args){
int i = 1;
while(i <= 100){
if (i % 3 == 0) {
System.out.println(i);
}
i++;
}
}
}
do...while循环控制
-
基本语法
循环变量初始化;
do{
循环体(语句);
循环变量迭代;
}while(循环条件); -
说明:
- do while 是关键字
- 同样有循环四要素,只是位置不同
- 先执行,再判断,也就是说,一定会执行一次
- 最后有个分号;
public class DoWhile{
public static void main(String[] args) {
//统计1-200之间能被5整除但不能被3整除的个数
int i = 1;
int count = 0;
do{
if (i % 5 == 0 && i % 3 != 0) {
System.out.println("i = " + i);
count++;
}
//不要忘记循环变量的迭代
i++;
}while(i <= 200);
System.out.println("个数为:" + count);
}
}
import java.util.Scanner;
public class DoWhile02{
public static void main(String[] args) {
// 如果不还钱,则一直问还钱吗,直到说还钱为止
// [System.out.println("还钱吗?y/n")] do...while ..
boolean flag = true;
Scanner myScanner = new Scanner(System.in);
char answer = ' ';
do{
System.out.println("还钱吗?y/n");
// public char charAt(int index)
// 返回指定索引处的 char 值。
answer = myScanner.next().charAt(0);
if (answer == 'y') {
System.out.println("他决定还钱");
flag = false;
}else{
System.out.println("他决定不还钱");
}
}while(flag);
}
}
多重循环控制
- 将一个循环放在另一个循环体内,就形成了嵌套循环。其中,for,while,do...while均可以作为外层循环和内层循环。(一般使用两层,最多不要超过三层,否则,代码的可读性会很差。)
- 实质上,嵌套循环就是把内层循环当成外层循环的循环体。当只有内层循环的循环条件为false时,才会完全跳出内层循环,才可结束外层的当次循环,开始下一次的循环。
- 设外层循环次数为m次,,内层为n次,则内层循环体实际上需要执行m*n次。
public class MulFor{
public static void main(String[] args) {
for (int i = 0;i < 2 ;i++ ) {
for (int j = 0;j < 3 ;j++ ) {
System.out.println("i = " + i + "j = " + j);
}
}
}
}
打印空心金字塔
public class Stars{
public static void main(String[] args) {
/*
打印空心金字塔
思路分析:
1.化繁为简,打印矩形
*****
*****
*****
*****
*****
2.打印半个金字塔
*
**
***
****
*****
3.打印整个金字塔
* //第一层1个* 2 * 1 - 1 有总层数-1个空格
*** //第二层3个* 2 * 2 - 1
***** //第三层5个* 2 * 3 - 1
******* //第四层7个* 2 * 4 - 1
********* //第五层9个* 2 * 5 - 1
4.打印空心金字塔
* //第一层1个* 2 * 1 - 1 有总层数-1个空格
* * //第二层2个* 2 * 2 - 1
* * //第三层2个* 2 * 3 - 1
* * //第四层2个* 2 * 4 - 1
********* //第五层9个* 2 * 5 - 1
5.先死后活:将层数5用变量totalLevel表示
*/
int totalLevel = 10;
for (int i = 1;i <= totalLevel ;i++ ) {//i表示层数
// 在打印*之前打印空格 空格数=总层数-当前层
for (int k = 1;k <= totalLevel - i ;k++ ) {
System.out.print(" ");
}
//控制每层打印*的个数
for (int j = 1;j <= 2 * i - 1 ;j++ ) {
//当前行的第一个位置是*,最后一个位置也是*,最后一层全部是*
if(j == 1 || j == 2 * i - 1|| i == totalLevel){
System.out.print("*");
}else{
System.out.print(" ");
}
}
// 每打印玩一行的*就换一行 println本身就会换行
System.out.println("");
}
}
}
打印空心菱形
public class Stars2{
public static void main(String[] args) {
/*
打印空心的菱形
*/
//定义从菱形顶部到菱形腰部的层数为half,那么总层数就是2*half-1
int half = 8;
//打印上半个空心菱形
for (int i = 1;i <= half ;i++ ) {
//控制每层打印的菱形外围空格数
for (int j = 1;j <= half - i;j++ ) {
System.out.print(" ");
}
//控制每层打印的*和空格数
for (int k = 1;k <= 2 * i - 1;k++ ) {
if (k == 1 || k == 2 * i - 1) {
System.out.print("*");
}else{
System.out.print(" ");
}
}
//打印完每一行进行换行
System.out.println("");
}
//打印下半个菱形
for (int l = half+1;l <= 2 * half - 1 ;l++ ) {
//控制每层打印的菱形外围空格数
for (int m = 1;m <= l - half;m++ ) {
System.out.print(" ");
}
//控制每层打印的*和空格数
/*
这里的n <= 2 * (2 * half - l) -1其中的(2 * half - l)相当于上面的i
*/
for (int n = 1;n <= 2 * (2 * half - l) -1 ;n++ ) {
if (n == 1 || n == 2 * (2 * half - l) -1) {
System.out.print("*");
}else{
System.out.print(" ");
}
}
//打印完每一行进行换行
System.out.println("");
}
}
}
跳转控制语句-break
- 基本介绍
break语句用于终止某个语句块的执行,一般使用在switch或者循环【for,while,do-while】中 - 基本语法:
{
......
break;
......
}
public class Break01{
public static void main(String[] args){
for (int i = 0;i < 10 ;i++ ) {
if (i == 3) {
break;
}
System.out.println("i = " + i);
}
System.out.println("退出for循环,继续执行");
}
}
- 注意事项
- break语句出现在多层嵌套的语句块中时,可以通过标签指明要终止的是哪一层语句块。
- 标签的基本使用
label1:{......
label2:{......
label3:{
...
break;
...
}
}
} - break语句可以指定退出哪层,如:break label1;
- label1是标签,名称自拟。
- break后指定到哪个label就退出到哪里。
- 在实际的开发中,尽量不要使用标签。
- 如果没有指定break,默认退出最近的循环体。
public class BreakDetail{
public static void main(String[] args){
label1:
for (int j = 0;j < 4 ;j++ ) {//外层for
label2:
for (int i = 0;i < 10 ;i++ ) {//内层for
if (i == 2) {
break label2;
}
System.out.println("i = " + i);
}
}
}
}
当break label1和break label2的时候的结果不同
import java.util.Scanner;
public class BreakExercise02{
public static void main(String[] args) {
/*
实现登录验证,有三次机会,如果用户名为"小明",密码"666"提示登录成功,
否则提示还有几次机会,使用for+break完成
*/
Scanner myScanner = new Scanner(System.in);
String name = "";
String password = "";
int chance = 3;//登陆一次,就少一次
for (int i = 1;i <= 3 ;i++ ) {
System.out.println("请输入用户名:");
name = myScanner.next();
System.out.println("请输入密码:");
password = myScanner.next();
//判断输入的用户名和密码是否正确
//字符串的内容比较,使用equals方法
//"小明".equals(name)使用这种方式可以避免空指针
if ("小明".equals(name)&&"666".equals(password)) {
System.out.println("登陆成功");
break;
}
//登录的机会减少一次
chance--;
System.out.println("你还有"+chance+"次登录机会");
}
}
}
跳转控制语句 continue
- continue语句用于结束本次循环,继续执行下一次循环。
- continue语句出现在多层嵌套的循环语句体中时,可以通过标签指明要跳过的是哪一层循环,这个和前面的标签的使用的规则一样。
- 基本语法:
{
......
continue;
......
}
public class Continue{
public static void main(String[] args){
int i = 1;
while(i <= 4){
i++;
if (i == 2) {
continue;
}
System.out.println("i = " + i);
}
}
}
跳转控制语句 return
一般使用在方法上,用于跳出所在的方法。
如:return用在主函数main方法上,退出程序。
练习
public class HomeWork01{
public static void main(String[] args) {
/*
某人有100,000元,每经过一次路口,需要交费,规则如下:
1)当现金>50000时,每次交5%
2) 当现金<50000时,每次交1000
编程计算该人可以经过多少次路口,使用whilebreak
*/
int count = 0;
double money = 100000;
while (money >= 1000){
if (money >= 50000) {
money = 0.95 * money;//money *= 0.95
count ++;
}else{
money = money - 1000;
count ++;
}
}
System.out.println("可以经过" + count + "次路口");
}
}
public class HomeWork02{
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 a = i / 100;
// 求十位
int b = (i % 100) / 10;
// 求个位
int c = i % 10;
if ((a * a * a + b * b * b + c * c * c )== i) {
System.out.println( i + "是水仙花数");
}
}
}
}
public class HomeWork03{
public static void main(String[] args) {
// 输出小写的a-z和大写的Z-A
for (char c1 = 'a'; c1 <= 'z' ;c1++ ) {
System.out.print(c1);
}
System.out.println("");
for (char c2 = 'Z'; c2 >= 'A' ;c2-- ) {
System.out.print(c2);
}
}
}
public class HomeWork04{
public static void main(String[] args) {
//打印1-1/2+1/3-1/4...1/100
double sum = 0;
for (int i = 1;i <= 100 ;i++ ) {
//判断是奇数还是偶数,做不同的处理
if (i % 2 != 0) {//分母为奇数
sum += 1.0/i;
//这里注意是1.0而不能是1,否则1/i当i大于1时的结果都是0
}else{//分母为偶数
sum -= 1.0/i;
}
}
System.out.println("sum = " + sum);
}
}
public class HomeWork05{
public static void main(String[] args) {
//求1+(1+2)+(1+2+3)+(1+2+3+4)+...+(1+2+3+...+100)的结果
int sum = 0;
for (int i = 1; i <= 100;i++ ) {
for (int j = 1;j <= i ;j++ ) {
sum += j;
}
}
System.out.println("sum =" + sum);//171700
}
}