Control Flow
# Comparison Operators
int x = 1;
int y = 1;
boolean equal = (x == y); // true
1
2
3
2
3
# Logical Operators
int temperature = 22;
boolean isWarm = temperature > 20 && temperature < 30; // true
boolean notWarm = temperature < 20 || temperature > 30; // true
boolean warm = !notWarm;
1
2
3
4
2
3
4
# If Statements
if (condition_1)
// blablabla
else if (condition_2)
// blablabla
else
// blablabla
boolean hasHighIncome = income > 100_000 ? true : false; // ❌
boolean hasHighIncome = income > 100_000; // ✅
// FizzBuzz
if (isFizz(number) && isBuzz(number))
sout("FizzBuzz");
else if (isFizz(number)) // even though there is repetition, its more readable and understandable than nested structure
sout("Fizz");
else if (isBuzz(number))
sout("Buzz");
else
sout(number);
public int isFizz(int number) {
return number % 5 == 0;
}
public int isBuzz(int number) {
return number % 3 == 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# The Ternary Operator
String className = (income > 100_000) ? "high" : "low";
1
# Switch Statements
switch (role) {
case "case_1":
// blablabla
break;
case "case_2":
// blablabla
break;
...
default:
// blablabla
}
// could be number
switch (role) {
case 1:
// blablabla
break;
case 2:
// blablabla
break;
...
default:
// blablabla
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# For Loops
for (int i = 0; i < something; i++) {
// blablabla
}
1
2
3
2
3
# While Loops
int i = 100;
while (i > 0) {
// blablabla
i --;
}
// running indefinitely
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
input = scanner.next().toLowerCase();
sout(input);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# Do..While Loops
Scanner scanner = new Scanner(System.in);
String input = "";
do {
input = scanner.next().toLowerCase();
sout(input);
} while (!input.equals("quit"))
1
2
3
4
5
6
7
2
3
4
5
6
7
# Break and Continue Statements
Scanner scanner = new Scanner(System.in);
String input = "";
while (true) { // condition can just be true
input = scanner.next().toLowerCase();
if (input.equals("quit"))
break;
if (input.equals("pass"))
continue;
sout(input);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# For-Each Loop
limitations:
- always forward going
- doesn't has access to index of items
String [] array = {"1", "2", "3"};
for (String number : array)
sout(number);
1
2
3
4
5
2
3
4
5
上次更新: 2021/12/31, 15:34:56