1. Java语言也会提供顺序、选择、循环等多种流程控制。
2. if语句可有三种表现形式。
- if (条件) {代码块}
public class A {
public static void main(String[] args){
int a = 5;
int b = 6;
int c = 4;
int m = a;
if (b > m){
m = b;
}
if (c > m){
m = c;
}
System.out.println(m);
}
}
输出6。
- 一般情况下,大括号内只有一句语句的时候,我们可以省略这个大括号。
- 当if语句代码块与条件不在同一行时,建议使用大括号。
- if的第二种常用形式当然是大家熟悉的if ... else ...
- if的第三种常用形式是多层else嵌套。
public class A {
public static void main(String[] args){
int x = 85;
if (x > 90) System.out.println("优秀");
else if (x > 80) System.out.println("良好");
else if (x > 70) System.out.println("中等");
else if (x > 60) System.out.println("及格");
else System.out.println("不及格");
}
}
输出良好。
3. 循环
- 死循环的写法:for( ; ;)与while(true)。
public class A {
public static void main(String[] args){
for ( ; ; ){
System.out.println("abc");
}
}
}
输出
abc
abc
abc
...。
public class A {
public static void main(String[] args){
while (true) {
System.out.println("abc");
}
}
}
输出
abc
abc
abc
...。
- 避免死循环,需要设定跳出条件。
public class A {
public static void main(String[] args){
int x = 0;
while (true) {
System.out.println(x);
x++;
if (x > 10) break;
}
}
}
输出
0
1
2
3
4
5
6
7
8
9
10。
public class A {
public static void main(String[] args){
int x = 0;
while (true) {
System.out.println("abc");
if (x > 10) break;
x++;
}
}
}
输出
0
1
2
3
4
5
6
7
8
9
10
11。
public class A {
public static void main(String[] args){
int x = 0;
while (true) {
if (x > 10) break;
System.out.println("abc");
x++;
}
}
}
输出
0
1
2
3
4
5
6
7
8
9
10。
- 经常的情况是先定义一个变量,给它赋一个初值,然后再做动作,然后判断退出循环条件,这就是for循环。
public class A {
public static void main(String[] args){
for (int i = 0; i < 10; i++){
System.out.println(i);
}
}
}
输出
0
1
2
3
4
5
6
7
8
9。
- 事实上,只用一种循环写法就可以解决所有循环问题。
public class A {
public static void main(String[] args){
boolean tag = true;
int n = 125;
for (int i = 2; i < n; i++){
if (n % i == 0) {
tag = false;
break;
}
}
System.out.println(tag);
}
}
输出false。
public class A {
public static void main(String[] args){
for (int n = 2; n <= 100; n++){
boolean tag = true;
for (int i = 2; i < n ; i++){
if (n % i == 0){
tag = false;
break;
}
}
if (tag) {
System.out.println(n);
}
}
}
}
输出
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97。
public class A {
public static void main(String[] args){
L1: for (int n = 2; n <= 100; n++){
for (int i = 2; i < n ; i++){
if (n % i == 0){
continue L1;
}
}
System.out.println(n);
}
}
}
输出
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97。