Java流程控制
用户交互Scanner
Scanner 对象
-
之前我们学的基本语法中并没有实现程序和人的交互,但是 Java 给我们提供了这样一个工具类,我们可以获取用户的输入。java.util.Scanner 是 Java5 的新特性,我们可以通过 Scanner 类来获取用户的输入
-
基本语法
Scanner s = new Scanner(System.in);
-
通过 Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,在读取前我们一般需要使用 hasNext() 与 hasNextLine() 判断是否还有输入的数据
next()
- 一定要读取到有效字符后才可以结束输入
- 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉
- 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符
- next() 不能得到带有空格的字符串
nextLine()
- 以 Enter 为结束符,也就是说 nextLine() 方法返回的是输入回车之前的所有字符
- 可以获得空白
package com.moon.study.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
// 创建一个扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收:");
// 判断用户有没有输入
// 输入 hello world 只接收到了 hello
if (scanner.hasNext()) {
// 使用next方式接收
String str = scanner.next();
System.out.println("输入的内容为:" + str); // 输入的内容为:hello
}
// 凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
scanner.close();
}
}
package com.moon.study.scanner;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方式接收:");
// 输入 hello world 可以全部接收到
if (scanner.hasNextLine()) {
// 使用nextLine方式接收
String str = scanner.nextLine();
System.out.println("输入的内容为:" + str); // 输入的内容为:hello world
}
scanner.close();
}
}
顺序结构
-
Java 的基本结构就是顺序结构,除非特别指明,否则就按照顺序一句一句执行
-
顺序结构是最简单的算法结构
- 语句与语句之间,框与框之间是按从上到下的顺序执行的,它是由若干个依次执行的处理步骤组成的,它是任何一个算法都离不开的一种基本算法结构
选择结构
if 单选择结构
-
我们很多时候需要去判断一个东西是否可行,然后我们才去执行,这样一个过程在程序中用 if 语句来表示
-
语法:
if(布尔表达式) { // 如果布尔表达式的值为true将执行的语句 }
if 双选择结构
语法:
if(布尔表达式) {
// 如果布尔表达式的值为true
} else {
// 如果布尔表达式的值为false
}
if 多选择结构
语法:
if(布尔表达式 1) {
// 如果布尔表达式 1 的值为true
} else if (布尔表达式 2) {
// 如果布尔表达式 2 的值为true
} else if (布尔表达式 3) {
// 如果布尔表达式 3 的值为true
} else {
// 如果以上的布尔表达式都不为true
}
package com.moon.study.struct;
import java.util.Scanner;
public class IfDemo01
{
public static void main(String[] args) {
// 分数等级,大于60及格,小于60不及格
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩:");
if (scanner.hasNextInt()) {
int score = scanner.nextInt();
if (score == 100) {
System.out.println("恭喜满分");
} else if (score < 100 && score >= 90) {
System.out.println("A级");
} else if (score < 90 && score >= 80) {
System.out.println("B级");
} else if (score < 80 && score >= 70) {
System.out.println("C级");
} else if (score < 70 && score >= 60) {
System.out.println("D级");
} else if (score < 60 && score >= 0) {
System.out.println("不及格");
} else {
System.out.println("成绩不合法");
}
}
scanner.close();
}
}
嵌套的 if 结构
-
使用嵌套的 if…else 语句是合法的。也就是说你可以在另一个 if 或者 else if 语句中使用 if 或者 else if 语句。你可以像 if 语句一样嵌套 else if…else
-
语法
if(布尔表达式 1) { //如果布尔表达式 1 的值为true if(布尔表达式 2) { //如果布尔表达式 2 的值为true } }
-
思考?我们需要寻找一个数,在1~100之间
switch 多选择结构
- 多选择结构还有一个实现的方式就是switch case 语句
- switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支
- switch 语句中的变量类型可以是:
- byte、short、int 或者 char
- 从 Java SE 7 开始,switch 支持字符串 String 类型,同时 case 标签必须为字符串常量或字面量
package com.moon.study.struct;
public class SwitchDemo01 {
public static void main(String[] args) {
// switch 匹配一个具体的值 注意避免 case 穿透
char grade = 'C';
switch (grade) {
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;
default:
System.out.println("未知等级");
}
}
}
循环结构
while 循环
-
while 是最基本的循环,它的结构为:
while(布尔表达式) { // 循环内容 }
-
只要布尔表达式为 true,循环就会一直执行下去
-
我们大多数情况下是会让循环停止下来的,我们需要一个让表达式失效的方式来结束循环
-
少部分情况下需要循环一直执行,比如服务器的请求响应监听等
-
循环条件一直为 true 就会造成无限循环(死循环),我们正常的业务编程中应该尽量避免死循环,会影响程序性能或造成程序卡死崩溃
package com.moon.study.struct;
public class WhileDemo01 {
public static void main(String[] args) {
// 输出 1~100
int i = 0;
while (i < 100) {
i ++;
System.out.println(i);
}
// 计算 1+2+3+...+100=?
int num = 0;
int sum = 0;
while (num <= 100) {
sum += num;
num++;
}
System.out.println(sum); // 5050
}
}
do…while 循环
-
对于 while 语句而言,如果不满足条件,则不能进入循环体。但有时候我们需要即使不满足条件,也至少执行一次
-
do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次
do { //代码语句 } while(布尔表达式);
-
while 和 do…while 区别:
- while 先判断后执行,do…while是先执行后判断
- do…while 总是保证循环体会被至少执行一次,这是他们的主要差别
package com.moon.study.struct; public class DoWhileDemo01 { public static void main(String[] args) { int i = 0; while (i < 0) { i++; } System.out.println(i); // 0 System.out.println("==============="); do { i++; } while (i < 0); System.out.println(i); // 1 } }
for 循环
在 Java 5 中引入了一种主要用于数组的增强型 for 循环
-
虽然所有的循环结构都可以用 while 或者 do…while 表示,但 Java 提供了另一种语句 — for 循环,使一些循环结构变得更加简单
-
for 循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构
-
for 循环执行的次数是在执行前就确定的
-
语法:
for(初始化; 布尔表达式; 更新) { // 代码语句 }
package com.moon.study.struct;
public class ForDemo01 {
public static void main(String[] args) {
// 初始化 条件判断 迭代
/*
* 最先执行初始化步骤。可以声明一种类型,可初始化一个或多个循环控制变量,也可以是空语句
* 然后,检测布尔表达式的值。为 true,循环体被执行;为 false,循环终止,开始执行循环体后面的语句
* 执行一次循环后,更新循环控制变量(迭代因子控制循环变量的增减)
* 再次检测布尔表达式,循环执行上面的过程
*/
// 计算 0~100 之间奇数和、偶数和
int oddSum = 0;
int evenSum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 != 0) {
oddSum += i;
} else {
evenSum += i;
}
}
System.out.println("奇数和:" + oddSum);
System.out.println("偶数和:" + evenSum);
// 循环输出1~1000之间能被 5 整除的数,并且每行输出 3 个
for (int i = 1; i < 1000; i++) {
if (i % 5 == 0) {
System.out.print(i + "\t"); // print 输出完不会换行
}
// 每行 3 个
if (i % (3 * 5) == 0) {
System.out.println(); // println 输出完会换行
}
}
// 打印九九乘法表
System.out.println("\n");
for (int j = 1; j <= 9; j++) {
for (int i = 1; i <= j; i++) {
System.out.print(j + "*" + i + "=" + (j * i) + "\t");
}
System.out.println();
}
}
}
增强for循环
-
Java 5 引入了一种主要用于数组或集合的增强型 for 循环
-
Java 增强 for 循环语法格式如下:
for (声明语句 : 表达式) { //代码语句 }
-
声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等
-
表达式:表达式是要访问的数组名,或者是返回值为数组的方法
package com.moon.study.struct;
public class ForDemo02 {
public static void main(String[] args) {
// 定义一个数组
int[] numbers = {10, 20, 30, 40, 50};
// 增强型for 遍历数组的元素
for (int x : numbers) {
System.out.println(x);
}
System.out.println("==============");
// 原始方式
for (int i = 0; i < 5; i++) {
System.out.println(numbers[i]);
}
}
}
break、continue、goto
-
break 在任何循环语句的主体部分,均可用 break 控制循环的流程。break 用于强行退出循环,不执行循环中剩余的语句(break 语句也在 switch 语句中使用)
-
continue 语句用在循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定
-
关于 goto 关键字
- goto 关键字很早就在程序设计语言中出现。尽管 goto 仍是 Java 的一个保留字,但并未在语言中得到正式使用;Java 没有 goto。然而,在break 和 continue 这两个关键字的身上,我们仍然能看出一些 goto 的影子—带标签的 break 和continue
- ”标签“ 是指后面跟一个冒号的标识符,例如:label:
- 对 Java 来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望在其中嵌套另一个循环,由于 break 和 continue 关键字通常只中断当前循环,但若随同标签使用,它们就会中断到存在标签的地方
package com.moon.study.struct;
public class BreakAndContinueDemo {
public static void main(String[] args) {
// break
int i = 0;
while (i < 100) {
i++;
System.out.println(i);
// 直接退出循环。只打印了 1~30
if (i == 30 ) {
break;
}
}
// continue
int r = 0;
while (r < 100) {
r++;
// 跳过本次循环,继续进行下一次循环。没有打印能被10整除的数
if (r % 10 == 0) {
System.out.println();
continue;
}
System.out.print(r + "\t");
}
}
}
package com.moon.study.struct;
public class LabelDemo {
public static void main(String[] args) {
// 标签
// 打印 101~150 之间所有的质数
// 质数:是指在大于 1 的自然数中,除了 1 和它本身以外不再有其他因数的自然数
outer: for (int i = 101; i <= 150; i++) {
for (int j = 2; j < i / 2; j++) {
if (i % j == 0) {
continue outer;
}
}
System.out.print(i + "\t");
}
}
}
练习
打印三角形
package com.moon.study.struct;
public class TestDemo {
public static void main(String[] args) {
// 打印三角形 5行
for (int i = 1; i <= 5; i++) {
// 倒三角
for (int j = 5; j >= i; j--) {
System.out.print(" ");
}
// 正三角
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}