廖雪峰java教程笔记-java流程控制


流程控制

输入输出

输出

1
2
System.out.println 换行
System.out.print 不换行

格式化输出

1
2
3
printf("%.3f", d)

%表示占位符,连续两个%%表示%

87yp26.png

输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
和输出相比,Java的输入就要复杂得多。
我们先看一个从控制台读取一个字符串和一个整数的例子:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // 创建Scanner对象
System.out.print("Input your name: "); // 打印提示
String name = scanner.nextLine(); // 读取一行输入并获取字符串
System.out.print("Input your age: "); // 打印提示
int age = scanner.nextInt(); // 读取一行输入并获取整数
System.out.printf("Hi, %s, you are %d\n", name, age); // 格式化输出
}
}
1
2
3
创建Scanner对象并传入System.in。System.out代表标准输出流,而System.in代表标准输入流。直接使用System.in读取用户输入虽然是可以的,但需要更复杂的代码,而通过Scanner就可以简化后续的代码。

有了Scanner对象后,要读取用户输入的字符串,使用scanner.nextLine(),要读取用户输入的整数,使用scanner.nextInt()。Scanner会自动转换数据类型,因此不必手动转换。
1
2
3
4
+ scanner.next 读取直到空格符
+ scanner.nextLine 读取一行
+ scanner.nextInt
+ scanner.nextDouble

小结

1
2
3
Java提供的输出包括:System.out.println() / print() / printf(),其中printf()可以格式化输出;

Java提供Scanner对象来方便输入,读取对应的类型可以使用:scanner.nextLine() / nextInt() / nextDouble() / ...

if判断

只有一条语句时可以省略华括号

if()

{
}

else if()

{
}

else

{
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
前面讲过了浮点数在计算机中常常无法精确表示,并且计算可能出现误差,因此,判断浮点数相等用==判断不靠谱
正确的方法是利用差值小于某个临界值来判断
public class Main {
public static void main(String[] args) {
double x = 1 - 9.0 / 10;
if (Math.abs(x - 0.1) < 0.00001) {
System.out.println("x is 0.1");
} else {
System.out.println("x is NOT 0.1");
}
}
}

x is 0.1

判断引用类型数据是否相等

1
在Java中,判断值类型的变量是否相等,可以使用==运算符。但是,判断引用类型的变量是否相等,==表示“引用是否相等”,或者说,是否指向同一个对象。例如,下面的两个String类型,它们的内容是相同的,但是,分别指向不同的对象,用==判断,结果为false:
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO".toLowerCase();
System.out.println(s1);
System.out.println(s2);
if (s1 == s2) {
System.out.println("s1 == s2");
} else {
System.out.println("s1 != s2");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
要判断引用类型的变量内容是否相等,必须使用equals()方法:
public class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO".toLowerCase();
System.out.println(s1);
System.out.println(s2);
if (s1.equals(s2)) {
System.out.println("s1 equals s2");
} else {
System.out.println("s1 not equals s2");
}
}
}
1
2
3
注意:执行语句s1.equals(s2)时,如果变量s1为null,会报NullPointerException

要避免NullPointerException错误,可以利用短路运算符&&
1
2
3
4
5
6
7
8
9
10
public class Main {
public static void main(String[] args) {
String s1 = null;
if (s1 != null && s1.equals("hello")) {
System.out.println("hello");
}
}
}

还可以把一定不是null的对象"hello"放到前面:例如:if ("hello".equals(s)) { ... }。

switch语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
switch(option)

{

case 1:
............;
break;

case 2:
............;
break;

default:(可以没有)

.....;

break;

}

新语法

1
2
3
4
case没有花括号,可以合理的增减break(具有 穿透性);比较字符串时是比较内容

switch新语法,可以不要break,没有穿透;case可以使用->
注意新语法使用->,如果有多条语句,需要用{}括起来。不要写break语句,因为新语法只会执行匹配的语句,没有穿透效应
87fFp9.png
1
2
3
4
5
6
7
8
9
10
11
12
使用新的switch语法,不但不需要break,还可以直接返回值。把上面的代码改写如下
public class Main {
public static void main(String[] args) {
String fruit = "apple";
int opt = switch (fruit) {
case "apple" -> 1;
case "pear", "mango" -> 2;
default -> 0;
}; // 注意赋值语句要以;结束
System.out.println("opt = " + opt);
}
}

case语句执行的是同一组语句块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
如果有几个case语句执行的是同一组语句块,可以这么写
public class Main {
public static void main(String[] args) {
int option = 2;
switch (option) {
case 1:
System.out.println("Selected 1");
break;
case 2:
case 3:
System.out.println("Selected 2, 3");
break;
default:
System.out.println("Not selected");
break;
}
}
}

匹配字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
switch语句还可以匹配字符串。字符串匹配时,是比较“内容相等”。

public class Main {
public static void main(String[] args) {
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("Selected apple");
break;
case "pear":
System.out.println("Selected pear");
break;
case "mango":
System.out.println("Selected mango");
break;
default:
System.out.println("No fruit selected");
break;
}
}
}

Selected apple

枚举类型

yield

1
2
3
在switch表达式内部,我们会返回简单的值。

但是,如果需要复杂的语句,我们也可以写很多语句,放到{...}里,然后,用yield返回一个值作为switch语句的返回值
87fUAS.png

小结

1
2
3
4
5
switch语句可以做多重选择,然后执行匹配的case语句后续代码;
switch的计算结果必须是整型、字符串或枚举类型;
注意千万不要漏写break,建议打开fall-through警告;
总是写上default,建议打开missing default警告;
从Java 14开始,switch语句正式升级为表达式,不再需要break,并且允许使用yield返回值。

while

1
2
while(xxx){
}

do….while

至少执行一次

1
2
3
do{

}while(xxx);

for(初始条件,循环条件,更新计数器)

1
2
3
4
5
6
7
除了while和do while循环,Java使用最广泛的是for循环。

for循环的功能非常强大,它使用计数器实现循环。for循环会先初始化计数器,然后,在每次循环前检测循环条件,在每次循环后更新计数器。计数器变量通常命名为i

for (初始条件; 循环检测条件; 循环后更新计数器) {
// 执行语句
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
使用for循环时,计数器变量i要尽量定义在for循环中:

int[] ns = { 1, 4, 9, 16, 25 };
for (int i=0; i<ns.length; i++) {
System.out.println(ns[i]);
}
// 无法访问i
int n = i; // compile error!
如果变量i定义在for循环外:

int[] ns = { 1, 4, 9, 16, 25 };
int i;
for (i=0; i<ns.length; i++) {
System.out.println(ns[i]);
}
// 仍然可以使用i
int n = i;
那么,退出for循环后,变量i仍然可以被访问,这就破坏了变量应该把访问范围缩到最小的原则
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for循环还可以缺少初始化语句、循环条件和每次循环更新语句,例如:

// 不设置结束条件:
for (int i=0; ; i++) {
...
}
// 不设置结束条件和更新语句:
for (int i=0; ;) {
...
}
// 什么都不设置:
for (;;) {
...
}
通常不推荐这样写,但是,某些情况下,是可以省略for循环的某些语句的

for each

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for(变量类型  变量名: 可迭代数据类型(list,map....))
可以直接遍历数组每个元素,计数器在for循环内部

public class Main {
public static void main(String[] args) {
int[] ns = { 1, 4, 9, 16, 25 };
for (int n : ns) {
System.out.println(n);
}
}
}

但是,for each循环无法指定遍历顺序,也无法获取数组的索引。

除了数组外,for each循环能够遍历所有“可迭代”的数据类型,包括后面会介绍的List、Map等

break和continue

break跳出所在的那层循环;continue结束当前循环,进入下一次循环

小结

1
2
3
4
5
break语句可以跳出当前循环;
break语句通常配合if,在满足条件时提前结束整个循环;
break语句总是跳出最近的一层循环;
continue语句可以提前结束本次循环;
continue语句通常配合if,在满足条件时提前结束本次循环

本文标题:廖雪峰java教程笔记-java流程控制

文章作者:TTYONG

发布时间:2022年02月10日 - 17:02

最后更新:2022年02月11日 - 12:02

原始链接:http://tianyong.fun/%E5%BB%96%E9%9B%AA%E5%B3%B0java%E6%95%99%E7%A8%8B%E7%AC%94%E8%AE%B0-java%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6.html

许可协议: 转载请保留原文链接及作者。

多少都是爱
0%