Table of contents
sequential structure
The sequence structure is relatively simple, and it is executed line by line according to the order in which the code is written.
System.out.println("aaa");
System.out.println("bbb");
System.out.println("ccc");
// 运行结果
aaa
bbb
ccc
If you adjust the writing order of the code, the execution order will also change
System.out.println("aaa");
System.out.println("ccc");
System.out.println("bbb");
// 运行结果
aaa
ccc
bbb
branch structure
if statement
Grammar Format 1
if(布尔表达式){
// 语句
}
If the Boolean expression evaluates to true, the statement in the if is executed, otherwise it is not executed.
For example: Xiao Ming, if you get a score of 90 or above in this test, I will reward you with a chicken leg.
int score = 92;
if(score >= 90){
System.out.println("吃个大鸡腿!!!");
}
Grammar format 2
if(布尔表达式){
// 语句1
}else {
// 语句2
}
If the result of the Boolean expression is true, execute the statement in the if, otherwise execute the statement in the else.
For example: Xiao Ming, if you score more than 90 points in this test, I will reward you with a big drumstick, otherwise you will be rewarded with a big mouth
int score = 92;
if(score >= 90){
System.out.println("吃个大鸡腿!!!");
}else{
System.out.println("挨大嘴巴子!!!");
}
Grammar format 3
if(布尔表达式1) {
// 语句1
}else if(布尔表达式2) {
// 语句2
}else {
// 语句3
}
If expression 1 is true, execute statement 1, otherwise expression 2 is true, execute statement 2, otherwise execute statement 3
For example: Considering the self-esteem of students, the score ranking is not disclosed, so:
Scores between [90, 100] are excellent
Scores before [80, 90) are good
Scores between [70, 80) are average
Scores between [60, 70) are good If the pass
score is between [0, 60), it is a fail
error data
According to the above method to notify students of grades, the code is as follows
if(score >= 90){
System.out.println("优秀");
}else if(score >= 80 && score < 90){
System.out.println("良好");
}else if(score >= 70 && score < 80){
System.out.println("中等");
}else if(score >= 60 && score < 70){
System.out.println("及格");
}else if(score >= 0 && score < 60){
System.out.println("不及格");
}else{
System.out.println("错误数据");
}
practise
exercise one
Determine if a number is odd or even
int num = 10;
if (num % 2 == 0) {
System.out.println("num 是偶数");
} else {
System.out.println("num 是奇数");
}
exercise two
Determine if a number is positive, negative, or zero
int num = 10;
if (num > 0) {
System.out.println("正数");
} else if (num < 0) {
System.out.println("负数");
} else {
System.out.println("0");
}
Exercise three
Check if a year is a leap year
int year = 2000;
if (year % 100 == 0) {
// 判定世纪闰年
if (year % 400 == 0) {
System.out.println("是闰年");
} else {
System.out.println("不是闰年");
}
} else {
// 普通闰年
if (year % 4 == 0) {
System.out.println("是闰年");
} else {
System.out.println("不是闰年");
}
}
Precautions
code style
Style 1 -----> Recommended
int x = 10;
if (x == 10) {
// 语句1
} else {
// 语句2
}
style 2
int x = 10;
if (x == 10)
{
// 语句1
}
else
{
// 语句2
}
Although both methods are legal, it is recommended to use style 1 in Java, { put on the same line as if / else. The code is more compact
semicolon problem
int x = 20;
if (x == 10);
{
System.out.println("hehe");
}
// 运行结果
hehe
An extra semicolon is written here, causing the semicolon to become the statement body of the if statement, and the code in { } has become a code block that has nothing to do with an if
dangling else question
int x = 10;
int y = 10;
if (x == 10)
if (y == 10)
System.out.println("aaa");
else
System.out.println("bbb");
You don’t need to put braces in the if / else statement. But you can also write a statement (you can only write one statement). At this time, else matches the closest if. But we don’t recommend writing this way in actual development. It’s better to add big parantheses.
switch statement
basic grammar
switch(表达式){
case 常量值1:{
语句1;
[break;]
}
case 常量值2:{
语句2;
[break;]
}
...
default:{
内容都不满足时执行语句;
[break;]
}
}
Implementation process
1. Calculate the value of the expression first
. 2. Compare with the case in turn. Once there is a corresponding match, execute the statement under the item until it encounters a break. 3.
When the value of the expression does not match the listed item, execute default
code example
Output the week according to the value of day
int day = 1;
switch(day) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期日");
break;
default:
System.out.println("输入有误");
break;
}
Precautions
1. The constant value after multiple cases cannot be repeated.
2. The brackets of the switch can only be the following types of expressions
Basic type: byte, char, short, int, note that it cannot be long type
Reference type: String constant string, enumeration type
double num = 1.0;
switch(num) {
case 1.0:
System.out.println("hehe");
break;
case 2.0:
System.out.println("haha");
break;
}
// 编译出错
Test.java:4: 错误: 不兼容的类型: 从double转换到int可能会有损失
switch(num) {
^
1 个错误
3. Do not miss break, otherwise the effect of "multi-branch selection" will be lost
int day = 1;
switch(day) {
case 1:
System.out.println("星期一");
// break;
case 2:
System.out.println("星期二");
break;
}
// 运行结果
星期一
星期二
4. Switch cannot express complex conditions
// 例如: 如果 num 的值在 10 到 20 之间, 就打印 hehe
// 这样的代码使用 if 很容易表达, 但是使用 switch 就无法表示.
if (num > 10 && num < 20) {
System.out.println("hehe");
}
5. Although switch supports nesting, it is ugly and generally not recommended
int x = 1;
int y = 1;
switch(x) {
case 1:
switch(y) {
case 1:
System.out.println("hehe");
break;
}
break;
case 2:
System.out.println("haha");
break;
}
The beauty of the code is also an important criterion. After all, this is a world of face
In summary, we found that the use of switch is relatively limited
loop structure
while loop
basic grammar format
while(循环条件) {
循环语句;
}
If the loop condition is true, execute the loop statement; otherwise end the loop
code example 1
prints the numbers 1 - 10
int num = 1;
while (num <= 10) {
System.out.println(num);
num++;
}
code example 2
Calculate the sum of 1 - 100
int n = 1;
int result = 0;
while (n <= 100) {
result += n;
n++;
}
System.out.println(num);
// 执行结果
5050
code example 3
Calculate the factorial of 5
int n = 1;
int result = 1;
while (n <= 5) {
result *= n;
n++;
}
System.out.println(num);
// 执行结果
120
code example 4
Calculate 1! + 2! + 3! + 4! + 5!
int num = 1;
int sum = 0;
// 外层循环负责求阶乘的和
while (num <= 5) {
int factorResult = 1;
int tmp = 1;
// 里层循环负责完成求阶乘的细节.
while (tmp <= num) {
factorResult *= tmp;
tmp++;
}
sum += factorResult;
num++;
}
System.out.println("sum = " + sum);
Here we find that when a code has multiple loops, the complexity of the code is greatly increased. And more complex code is more error-prone, and we will use a simpler method to solve this problem later.
Precautions
1. Similar to if, the statement below while can not write { }, but only one statement can be supported when not written. It is recommended to add { } 2.
Similar to if, the { after while is recommended to be written on the same line as while 3.
Similar to if, do not write more semicolons after while, otherwise the loop may not be executed correctly.int num = 1; while (num <= 10); { System.out.println(num); num++; } // 执行结果 [无任何输出, 程序死循环]
At this time; is the statement body of while (this is an empty statement), and the actual { } part has nothing to do with the loop. At this time, the loop condition num <= 10 is always true, resulting in an infinite loop of code.
break
The function of break is to let the loop end early
code example
Find the first multiple of 3 from 100 - 200
int num = 100;
while (num <= 200) {
if (num % 3 == 0) {
System.out.println("找到了 3 的倍数, 为:" + num);
break;
}
num++;
}
// 执行结果
找到了 3 的倍数, 为:102
Execution to break will end the loop.
Note: break can only jump out of one layer of loops, if you need to jump out of multiple layers of loops, you need multiple breaks
continue
The function of continue is to skip this cycle and immediately enter the next cycle
code example
Find all multiples of 3 from 100 - 200
int num = 100;
while (num <= 200) {
if (num % 3 != 0) {
num++; // 这里的 ++ 不要忘记! 否则会死循环.
continue;
}
System.out.println("找到了 3 的倍数, 为:" + num);
num++;
}
When the continue statement is executed, it will immediately enter the next loop (determine the loop condition), so that the print statement below will not be executed.
for loop
basic grammar
for(表达式①;布尔表达式②;表达式③){
表达式④;
}
Expression 1: It is used to initialize the initial value setting of the loop variable, which is executed at the very beginning of the loop, and only once.
Expression 2: The loop condition, if it is full, the loop continues, otherwise the loop ends.
Expression 3: The loop variable update method
Implementation process
①②③④--->②③④--->②③④--->②③④--->②③④--->②③④--->...--->② is false, the loop ends
code example
example one
1. Print the numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
Example two
2. Calculate the sum of 1 - 100
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("sum = " + sum);
// 执行结果
5050
Example three
3. Calculate the factorial of 5
int result = 1;
for (int i = 1; i <= 5; i++) {
result *= i;
}
System.out.println("result = " + result);
Example four
4. Calculate 1! + 2! + 3! + 4! + 5!
int sum = 0;
for (int i = 1; i <= 5; i++) {
int tmp = 1;
for (int j = 1; j <= i; j++) {
tmp *= j;
}
sum += tmp;
}
System.out.println("sum = " + sum);
Precautions
1. Similar to if, { } can be omitted for the statement below for, but only one statement is supported when not written. It is recommended to add { } 2.
Similar to if, the { after for is recommended to be written on the same line as while 3.
Similar to if, do not write more semicolons after for, otherwise the loop may not be executed correctly.
4. Like the while loop, use continue to end a single loop, and break to end the entire loop
do while loop
basic grammar
do{
循环语句;
}while(循环条件);
Execute the loop statement first, and then determine the loop condition. If the loop condition is met, continue to execute, otherwise the loop ends
code example
print 1 - 10
int num = 1;
do {
System.out.println(num);
num++;
} while (num <= 10);
Precautions
1. Do not forget the semicolon at the end of the do while loop
2. Generally, do while is rarely used, and it is recommended to use for and while
input Output
output to the console
basic grammar
System.out.println(msg); // 输出一个字符串, 带换行
System.out.print(msg); // 输出一个字符串, 不带换行
System.out.printf(format, msg); // 格式化输出
The output content of println comes with \n, and print does not have \n.
The formatted output method of printf is basically the same as that of printf in C language.
code example
System.out.println("hello world");
int x = 10;
Systm.out.printf("x = %d",x);
format string
conversion character | type | example | |
d | decimal integer | ("%d", 100) | 100 |
x | hexadecimal integer | ("%x", 100) | 64 |
o | octal integer | ("%o", 100) | 144 |
f | fixed point floating point | ("%f", 100f) | 100.000000 |
e | exponent float | ("%e", 100f) | 1.000000e+02 |
g | general floating point | ("%g", 100f) | 100.000 |
a | hex float | ("%a", 100) | 0x1.9p6 |
s | string | ("%s", 100) | 100 |
c | character | ("%c", ‘1’) | 1 |
b | Boolean value | ("%b", 100) | true |
h | hash code | ("%h", 100) | 64 |
% | percent sign | ("%.2f%%", 2/7f) | 0.29% |
input from the keyboard
Use Scanner to read strings/integers/floats
import java.util.Scanner; // 需要导入 util 包
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的姓名:");
String name = sc.nextLine();
System.out.println("请输入你的年龄:");
int age = sc.nextInt();
System.out.println("请输入你的工资:");
float salary = sc.nextFloat();
System.out.println("你的信息如下:");
System.out.println("姓名: "+name+"\n"+"年龄:"+age+"\n"+"工资:"+salary);
sc.close(); // 注意, 要记得调用关闭方法
// 执行结果
请输入你的姓名:
张三
请输入你的年龄:
18
请输入你的工资:
1000
你的信息如下:
姓名: 张三
年龄:18
工资:1000.0
Use Scanner to read N numbers in a loop and calculate their average
Scanner sc = new Scanner(System.in);
int sum = 0;
int num = 0;
while (sc.hasNextInt()) {
int tmp = sc.nextInt();
sum += tmp;
num++;
}
System.out.println("sum = " + sum);
System.out.println("avg = " + sum / num);
sc.close();
// 执行结果
10
40.0
50.5
^Z
sum = 150.5
avg = 30.1
Note: When entering multiple data in a loop, use ctrl + z to end the input (ctrl + z on Windows, ctrl + d on Linux / Mac)
guess the number game
game rules
The system automatically generates a random integer (1-100), and then the user enters a guessed number. If the input number is smaller than the random number, it will prompt "low", if the input number is larger than the random number, it will prompt "high" ", if the input number is equal to the random number, it will prompt "guess right"
Reference Code
import java.util.Random;
import java.util.Scanner;;
class Test {
public static void main(String[] args) {
Random random = new Random(); // 默认随机种子是系统时间
Scanner sc = new Scanner(System.in);
int toGuess = random.nextInt(100);
// System.out.println("toGuess: " + toGuess);
while (true) {
System.out.println("请输入要输入的数字: (1-100)");
int num = sc.nextInt();
if (num < toGuess) {
System.out.println("低了");
} else if (num > toGuess) {
System.out.println("高了");
} else {
System.out.println("猜对了");
break;
}
}
sc.close();
}
}
practise
1. According to age, the people who print out the current age are juvenile (below 18), youth (19-28), middle-aged (29-55), old age (above 56) 2. Determine whether a number is a prime number
3
. Print all prime numbers between 1 - 100
4. Output all leap years between 1000 - 2000
5. Output multiplication table
6. Find the greatest common divisor of two positive integers
7. Find all "narcissus" between 0 and 999 Number of flowers" and output. ("Narcissus number" refers to a three-digit number, and the cube sum of its digits is exactly equal to the number
itself, such as: 153=1^3+5^3+3^3, then 153 is a "Daffodils number".)
8 . Write a function to return the number of 1s in the parameter binary
. For example: 15 0000 1111 4 1s
9. Obtain all the even and odd bits in the binary sequence of a number, and output the binary sequence respectively.
Summarize
This is the end of the explanation of "Program Logic Control". You are welcome to leave a message for exchange and criticism. If the article is helpful to you or you think the author's writing is not bad, you can click to follow, like, and bookmark to support.