java control flow learning

java process control learning

Scanner object

concept

1. Realize the interaction between the program and people through the Scanner class, and obtain the user's input through it. java.util.Scanner is a feature of java5.

We can get user input through Scanner class .

2. Basic Grammar

Scanner s = new Scanner(System.in);

3. Use the next () and nextLine () methods of the Scanner class to obtain the input string. Before reading, you generally need to use hasNext () and hasNextLine () to determine whether there is input data.

Code display

After the keyboard input is complete, click Enter to complete the input.

Obtain the input value by the following method.

1. The next () access to the input data encounters a space, then it ends, and the value after the space cannot be obtained.

Use hasNext () method to determine whether the user enters a value.

String str = scanner.next (); After the program is executed, it will keep running. This code waits for the user to enter the value, and the next sentence will be executed after clicking the Enter key.

// 创建一个扫描器对象,用户接收键盘数据
// System.in表示输入,键盘输入数据传给Scanner类,使用scanner变量引用
Scanner scanner = new Scanner(System.in);

// 判断用户是否输入字符串
if(scanner.hasNext()) {
    // 程序执行后,会保持运行状态,这一句等待用户输入值,点击Enter结束后才会执行下一句
    String str = scanner.next();
    // 若输入12 45,结果为12,遇到空格后结束
    System.out.println("使用next结果为:" + str);
}
        
// 凡是属于IO(输入输出)流的类如果不关闭会一直占用资源,要养成关闭的习惯
scanner.close();

2. The nextLine () method gets all the data before clicking Enter.

Scanner scanner = new Scanner(System.in);

// 判断用户是否输入字符串
if(scanner.hasNextLine()) {
    String str = scanner.nextLine();
    // 若输入ab cd,结果为ab cd
    System.out.println("使用nextLine结果为:" + str);
}
        
scanner.close();

Features of two methods:

next()

1. Be sure to read valid characters before ending the input.

2. When a space is encountered, it ends, and only the string before the space can be obtained

3. next () cannot enter a string with spaces

nextLine()

1. With Enter as the end character, you can get all the characters you entered before clicking Enter.

2. You can get spaces and characters after spaces.

Scaner Advanced

Specify the type of input. For example, the specified input number type is valid.

Scanner scanner = new Scanner(System.in);      
double sum = 0;
int n = 0;

System.out.println("请输入数字类型,输入其他类型值加Enter未结束:");

// 只有输入不是数字类型后才能结束while循环,
// nextDouble只能获取到数字类型的值
while(scanner.hasNextDouble()) {
    double a = scanner.nextDouble();
    sum = sum + a;
    n++;
}

System.out.println("输入的数值的个数为:" + n);
System.out.println("输入值的平均值为:" + sum/n);

// 凡是属于IO(输入输出)流的类如果不关闭会一直占用资源,要养成关闭的习惯
scanner.close();

Sequential structure

The basic structure of java is a sequential structure. Unless otherwise specified, it will be executed sentence by sentence in sequence .

Sequential structure is a basic algorithm structure indispensable to any algorithm.

Judgment structure

Judge whether something is feasible before it is executed. The program uses an if statement to indicate the judgment structure.

grammar

// 布尔表达式:指结果为true或者false的表达式
if(布尔表达式) {
    // 布尔表达式为true时执行的括号里的语句
}

Double choice structure

There are two results after the judgment. grammar:

if(布尔表达式) {
    // 布尔表达式为true时执行语句
} else {
    // 布尔表达式为false时执行语句
}

Multiple choice structure

There are multiple condition judgments, as long as one condition is met, the subsequent judgment will not be executed.

grammar:

if (布尔表达1) {
    // 符合布尔表达式1为true就执行这里
} else if (布尔表达2) {
    // 符合布尔表达2为true就执行这里
} else if (布尔表达3) {
    // 符合布尔表达式3为true就执行这里
} else {
    // 都不符合布尔表达的1、2、3就执行这里
}
if (grade >= 90 && grade <=100) {
    System.out.println("成绩优秀!");
} else if (grade >= 80 && grade < 90) {
    System.out.println("成绩良好!");
} else if (grade >= 60 && grade <80) {
    System.out.println("成绩合格!");
} else if (grade >= 0 && grade < 60) {
    System.out.println("成绩不合格!");
} else {
    System.out.println("输入的成绩错误!");
}

Nested if structure

The judgment statement if can be used in the judgment statement if.

grammar

if (布尔表达式1) {
    // 布尔表达式1位true后执行
    if (布尔表达式2) {
        // 布尔表达式2位true后执行
    }
}

Switch

Switch is a multiple choice structure.

The variable type in the switch statement can be:

byte, short, int or char,

Starting from java SE 7, switch supports string type String.

At the same time, the case label must be a string constant.

grammar

// 表达式等于value值才会执行相应的语句
switch (表达式) {
    case value1 :
        // 表达式等于value1时执行这里的语句
        
        // break:执行后结束直接跳出,不会再执行后面的代码。
        break;
    case value2 :
        // 表达式等于value1时执行这里的语句
        break;
    default :
        // 表达式都不等于前面的value值时,执行这里
}
char grade = 'B';
switch (grade) {
    case 'A':
        System.out.println("成绩优秀!");
        break;
    case 'B':
        System.out.println("成绩良好!");
        break;
    case 'C':
        System.out.println("成绩及格!");
        break;
    default :
        System.out.println("不在成绩值的范围!");
}

The essence of judging whether it is equivalent in the switch is still judged by the value. The strings are the corresponding numbers in the unicode table. Each object has a hascode (composed of numbers) value, which is used to compare with the value's hascode. If they are equal, the statement under the value is executed.

java compilation java ---> class (bytecode file) ---> decompilation (IDEA)

Check the class file generated after java, decompile it through IDEA, and compare it with the original java file.

1. Right-click and select Project Structre

2. Find the path to the class file

3. Find the class file (I wrote the code in Demo03, so I chose to copy Demo03.class) to copy

Find the directory of the current file in IDEA

1. Right-click on the selected file

2. Select Show in Explorer to open the directory of the java file

3. Copy and paste the class file

The essence of the character is still the value, and the final judgment is still based on the value.

Cyclic structure

While

1. While is the most basic loop, its syntax is:

while(布尔表达式) {
    // 布尔表达式为true执行循环内容
}

2. As long as the Boolean expression is true, the loop will continue to execute.

3. In most cases , we will stop the loop, and we need a way to make the expression false to end the loop.

Calculate 1 ~ 100 with while

int sum = 0;
int i = 1;

// 只要i小于等于100就会一直执行while里面的语句
while(i <= 100) {
    sum = sum + i;
    i++;
}
// 当while中i大于100就会结束while循环,执行下一句代码。
System.out.println("结构和为:" + sum);

do~while

1. The do ... while loop is similar to the while loop, except that the do ... while loop will be executed at least once.

do {
    // 执行代码
} while(布尔表达式);

The difference between while and do ... while

1. While is judged before execution, while do ... while is judged after execution.

2. do ... while ensures that the loop is executed at least once.

for loop

1. The for loop statement is a general structure that supports iteration and is the most effective and flexible loop structure. The syntax is as follows:

for(初始化;布尔表达式;更新) {
    // 代码语句
}

Case: output the integer sum of 1 ~ 100

int sum = 0;
for (int i = 1;i <= 100;i++) {
    sum = sum + i;
}

Exercise 1: Output odd and even sums between 1 and 100

int odd = 0;  // 奇数
int even = 0; // 偶数
for (int i = 1;i <= 100;i++) {
    if (i%2 == 0) {
        even = even +i;
    } else {
        odd = odd +i;
    }
}

System.out.println("奇数和为:" + odd);
System.out.println("偶数和为:" + even);

Exercise 2: Output a value that is divisible by 5 within 100, and output 3 values ​​per line

for (int i=1;i <= 100;i++) {
    if(i%5 == 0) {
        System.out.print(i + " ");
    }
    if(i%(5*3) == 0) {
        System.out.println();
    }
}

Exercise 3: Print the ninety-nine nine multiplication table

// 练习:打印九成九乘法表
// 第一行打印1*1=1,结束后分行。
// 第二行打印1*2=2,2*2=3,结束后分行。
// 第三行...,
for (int i = 1;i <= 9;i++) {
    for (int j = 1;j <= i; j++) {
        System.out.print(j + "*" + i + "=" + (j*i) + "\t");
    }
    System.out.println();
}

Exercise 4: Printing triangles

// 打印三角形
for (int i = 1;i <= 5;i++) {
    for (int j = 5;j >= i;j--) {
        System.out.print(" ");
    }
    for (int n = 1;n <= i;n++) {
        System.out.print("*");
    }
    for (int m = 1;m < i;m++) {
        System.out.print("*");
    }
    System.out.println();
}

Enhanced for loop

1. java5 introduces an enhanced for loop mainly used for arrays or collections. The syntax is as follows

for (声明语句 : 表达式) {
    // 执行代码
}

2. Declaration statement: declare a new local variable whose type must match the type of the array element. The scope (that is, the range that can be used) is limited to the loop block (that is, the code in {}), and its value is equal to the value of the array element at this time.

3. Expression: The name of the array to be accessed, or the method of returning the value as an array.

int[] num = {10,20,30,40,50,60};

// 数组num的值会一个一个的传个a,全部传完后结束循环
for (int a : num) {
    System.out.println(a);
}
System.out.println("=====================");
// 相当于
int a;
for (int i = 0;i < num.length;i++) {
    a = num[i];
    System.out.println(a);
}

break和continue

1. break In the subject part of any loop statement, break is used to force quit to end the loop. (Mainly used in switch)

2. The continu statement is used in the loop statement body to terminate the current round of the loop, but the loop is not over, and the next round of the loop will be executed.

int i = 0;
while (i < 5) {
    i++;
    if (i == 3) {
        // 结束while循环,跳出执行下一句
        break;
    }
    System.out.print(i + " ");
}
//  结果为1 2

int j = 0;
while (j < 5) {
    j++;
    if (j == 3) {
        // 直接结束本次循环,会在执行下一个循环
        continue;
    }
    System.out.print(j + " ");
}
// 结果为1 2 4 5

Learning to watch the video is: Crazy God said java zero-based learning

Guess you like

Origin www.cnblogs.com/zhouyongyin/p/12677781.html