Java basics 02
5. Basic grammar (Part 2)
5.1 procedure flow control
Process control statements are statements used to control the execution order of statements in the program. Statements can be combined into small logic modules that can complete certain functions.
Its process control mode adopts three basic process structures specified in structured programming, namely
- Sequential structure
- The program is executed line by line from top to bottom without any judgment and jump
- Branching structure
- Selectively execute a piece of code according to conditions
- There are two branch statements: if else and switch case
- Cyclic structure
- Execute a piece of code repeatedly according to the loop conditions
- There are three loop statements: while, do... While and for
- Note:
- JDK1.5 provides a foreach loop to easily traverse sets and array elements.
5.1.1 branch structure
5.1.1.1,if-else
if statements have three formats:
1. If (conditional expression){
Execute code block;
}
If (conditional expression){
Execute code block 1;
}else{
Execute code block 2;
}
If (conditional expression 1){
Execute code block 1;
} else if (conditional expression 2){
Execute code block 2;
}
......
else{
Execute code block n;
}
Choose one
If else in branch structure
1. Three structures
First:
if(Conditional expression){ Execute code block; } Second: choose one from two if(Conditional expression){ Execute code block 1; }else{ Execute code block 2; } Third: choose one more if(Conditional expression 1){ Execute code block 1; }else if(Conditional expression 2){ Execute code block 2; } ...... else{ Execute code block n; }
5.1.1.2 Scanner class (supplementary)
How to get different types of variables from the keyboard: you need to use the Scanner class
Specific implementation steps:
1. Guide Package
import java.util.Scanner;
2. Instantiation of Scanner
Scanner sc = new Scanner(System.in);
3. Call the relevant methods of the Scanner class to obtain the variables of the specified type
int num = sc.nextInt(); System.out.println(num);
Scanner sc = new Scanner(System.in); System.out.println("Please enter your name:"); String name = sc.next(); System.out.println(name); System.out.println("Please enter your age:"); int age = sc.nextInt(); System.out.println(age); System.out.println("Please enter your weight:"); double weight = sc.nextDouble(); System.out.println(weight); sc.close();
For the acquisition of char type, Scanner does not provide relevant methods. Only one string can be obtained
Get only one character, using charAt();
System.out.println("Please enter your gender:(male/female)"); String gender = sc.next(); char genderChar = gender.charAt(0); //Gets the character at position with index 0 System.out.println(genderChar); sc.close();
When nextInt() is used, but the user enters double type, InputMismatchException will appear. If the input content does not match, the program will terminate directly.
be careful:
- You need to input the value of the specified type according to the corresponding method. If the input data type does not match the required type, an exception inputmismatch exception will be reported, resulting in the termination of the program.
5.1.1.3 switch case of branch structure II
switch(expression){ case Constant 1: Statement 1; //break; case Constant 2: Statement 2; //break; ... ... case constant N: sentence N; //break; default: sentence; //break; }
break is not necessary. It depends on the actual situation
int number = 2; switch(number) { case 0: System.out.println("zero"); case 1: System.out.println("one"); case 2: System.out.println("two"); case 3: System.out.println("three"); default: System.out.println("other"); } //result: two three other
explain:
-
Match the constants in each case in turn according to the value in the switch expression. Once the match is successful, it enters the corresponding case structure and calls its execution statement.
After the execution statement is called, the execution statements in other case structures are still executed downward until the break keyword is encountered or the end of this switch case structure is reached.
-
break, which can be used in the switch case structure, means that once this keyword is executed, it will jump out of the switch case structure.
-
switch(number)
- The expression in the switch structure can only be one of the following six data types
- byte
- short
- char
- int
- Enumeration type (new in JDK5.0)
- String type (new in JDK7.0)
- The expression in the switch structure can only be one of the following six data types
Application example of switch statement
String season = "summer"; switch(season) { case "spring": System.out.println("in the warm spring , flowers are coming out with a rush"); break; case "summer": System.out.println("Summer heat"); break; case "autumn": System.out.println("fresh autumn weather"); break; case "winter": System.out.println("Snow in winter"); break; default: System.out.println("Incorrect input"); break; } }
-
After case, you can only declare constants, not ranges.
-
break keyword
- Optional
-
default
- It is equivalent to else in if else structure
- The default structure is optional and the location is flexible.
5.1.2 circulation structure
When certain conditions are met, the function of specific code is executed repeatedly
Circular statement classification:
- for loop
- while Loop
- do-while Loop
The four components of a circular statement
- Init_statement
- Cycle condition part (test_exp)
- Body_statement
- Alter_statement
5.1.2.1 for loop
Use of for loop structure
1, Four elements of circular structure
- Initialization condition
- Loop condition -------- > is of boolean type
- Circulatory body
- Iterative condition
2, Structure of for loop
for(①;②;④){
③
}
Execution process: ① – > ② – > ③ – > ④ – > ② – > ③ – > ④ – >... ②
for(int i = 0;i < 5;i++) { System.out.println("Hello World!"); }
i is valid within the for loop, and it will fail after the for loop.
practice:
int j=1; for(System.out.print('a');j<3;j++,System.out.print('c')) { System.out.print('b'); } result: abcbc
Example:
Traverse even numbers within 100 and output the sum of all even numbers
int sum = 0; int count = 0; for(int i = 1;i <= 100;i++) { if(i%2==0) { System.out.println(i); sum += i; count++; } } System.out.println(count); System.out.println(sum); result: 50 2550
5.1.2.2. while cycle
Structure of while loop
①
while(②){
③;
④;
}
Execution process:
①–>②–>③–>④–>②–>③–>④–>...–>②
explain:
1. When writing a while loop, don't lose the iteration condition. Once lost, it may lead to an endless loop!
2. We write programs to avoid dead cycles.
3. for loop and while loop can be converted to each other!
Algorithm: finiteness.
//Traverse all even numbers within 100 int i = 1; while(i<=100) { if(i%2==0) { System.out.println(i); } i++; } except while After the loop, it can still be called.
difference:
The scope of the initialization condition part of the for loop and the while loop is different.
5.1.2.3 do while cycle
1, Four elements of circular structure
- Initialization condition
- Loop condition -------- > is of boolean type
- Circulatory body
- Iterative condition
2, Do while loop structure
①
do{
③;
④;
}while(②);
Execution process: ① – > ③ – > ④ – > ② – >... - > ②
explain:
1. The do while loop will execute the loop body at least once!
2. In development, use for and while more. Less use of do while
//Traverse all even numbers within 100 int i = 1; do{ if(i%2==0) { System.out.println(i); } i++; }while(i<=100);
5.1.3 comprehensive examples of circular sentences
The simplest "infinite" loop format: while(true),for(; 😉, The reason for the existence of infinite loop is that we don't know how many times the loop is. We need to control the end of the loop according to some conditions inside the loop body.
Title:
Read an uncertain number of integers from the keyboard, and judge the number of positive and negative numbers. Enter 0 to end the program.
Scanner sc = new Scanner(System.in); int positiveNumber = 0;//Record the number of positive numbers int negativeNumber = 0;//Record the number of negative numbers while(true) { //for(;;){ //Same effect int num = sc.nextInt(); //Judge the positive and negative of number if(num>0) { positiveNumber++; }else if(num<0) { negativeNumber++; }else { //Once the break is executed (enter 0), the loop jumps out. break; } } System.out.println(positiveNumber); System.out.println(negativeNumber);
explain:
- Structure that does not limit the number of times in the cycle condition part:
- for(;;) Or while(true)
- How many ways to end the cycle?
- Method 1: the loop condition part returns false
- Method 2: execute break in the loop body
5.1.4 nested loops (multiple loops)
Generally no more than three floors
1. Nested loop:
A nested loop is formed by declaring a loop structure a in the loop body of another loop structure B.
2,
Outer query
inner loop
explain:
- The inner loop structure is traversed once, which is only equivalent to the execution of the outer loop body once
- Suppose that the outer loop needs to be executed m times and the inner loop needs to be executed n times. At this time, the loop body of the inner loop has been executed m*n times
4. Skill
The outer loop controls the number of rows and the inner loop controls the number of columns
Output of all prime numbers within 100
Prime number:
- Prime, a natural number that can only be divided by 1 and itself.
- From 2 to the end of the number - 1, it can't be divided
The smallest prime number is 2
public static void main(String[] args) { boolean isFlag = true; for(int i = 2;i <= 100; i++) { for(int j = 2; j < i;j++) { if(i % j == 0) { isFlag = false; } } if(isFlag == true) { System.out.println(i); } //Reset isFlag isFlag = true; } }
Optimization 1:
boolean isFlag = true; //Gets the number of milliseconds between the current time and 1970-01-01 00:00:00 long start = System.currentTimeMillis(); for(int i = 2;i <= 100000; i++) { for(int j = 2; j < i;j++) { if(i % j == 0) { isFlag = false; break;//Optimization 1: it is only effective for natural numbers that are not prime numbers } } if(isFlag == true) { System.out.println(i); } //Reset isFlag isFlag = true; } //Gets the number of milliseconds between the current time and 1970-01-01 00:00:00 long end = System.currentTimeMillis(); System.out.println(end-start); //24905 before break optimization //2287 after break optimization }
Optimization 2:
public static void main(String[] args) { boolean isFlag = true; //Gets the number of milliseconds between the current time and 1970-01-01 00:00:00 long start = System.currentTimeMillis(); for(int i = 2;i <= 100000; i++) { for(int j = 2; j <= Math.sqrt(i);j++) { /* Optimization 2: j < Math.sqrt(i) Why? It is effective for natural numbers that are prime numbers */ if(i % j == 0) { isFlag = false; break;//Optimization 1: it is only effective for natural numbers that are not prime numbers } } if(isFlag == true) { System.out.println(i); } //Reset isFlag isFlag = true; } //Gets the number of milliseconds between the current time and 1970-01-01 00:00:00 long end = System.currentTimeMillis(); System.out.println(end-start); //Before break Optimization: 24905 //After break Optimization: 2287 //After optimization 2: 92 }
5.1.5 use of special keywords break and continue
keyword | Scope of use | Functions used in the loop (different points) | Same point |
---|---|---|---|
break: | switch-case | End current cycle | You cannot declare an execution statement after a keyword |
In cyclic structure | |||
continue | In cyclic structure | End the current cycle | You cannot declare an execution statement after a keyword |
for(int i = 1;i <= 10; i++) { if(i % 4 == 0) { break; } System.out.println(i); } result: 1 2 3
for(int i = 1;i <= 10; i++) { if(i % 4 == 0) { continue; } System.out.println(i); } result: 1 2 3 5 6 7 9 10
public static void main(String[] args) { for(int i = 1;i <= 4;i++) { for(int j = 1; j <= 10;j++) { if(j % 4 == 0) { break; //By default, the nearest loop of this keyword will pop up. } System.out.print(j); } System.out.println(); } } result: 123 123 123 123
public static void main(String[] args) { for(int i = 1;i <= 4;i++) { for(int j = 1; j <= 10;j++) { if(j % 4 == 0) { continue; //By default, it will jump out of the current cycle of the nearest layer of the package keyword. } System.out.print(j); } System.out.println(); } } result: 123567910 123567910 123567910 123567910
public static void main(String[] args) { label:for(int i = 1;i <= 4;i++) { for(int j = 1; j <= 10;j++) { if(j % 4 == 0) { break label; //Ends the one-layer loop structure of the specified ID. } System.out.print(j); } System.out.println(); } } result: 123
public static void main(String[] args) { label:for(int i = 1;i <= 4;i++) { for(int j = 1; j <= 10;j++) { if(j % 4 == 0) { continue label; //End the current cycle of the one-layer cycle structure of the specified ID. } System.out.print(j); } System.out.println(); } } result: 123123123123
Prime number method 2:
public static void main(String[] args) { int count = 0; long start = System.currentTimeMillis(); label:for(int i = 2;i <= 100000; i++) { for(int j = 2; j <= Math.sqrt(i);j++) { if(i % j == 0) { continue label; } } //This step is performed by prime numbers count++; } //Gets the number of milliseconds between the current time and 1970-01-01 00:00:00 long end = System.currentTimeMillis(); System.out.println(count); System.out.println(end-start); //Before break Optimization: 24905 //After break Optimization: 2287 //Optimization: 92 //At this time: 62 }
5.2 project I
Home accounting software
public static void main(String[] args) { boolean isFlag = true; //Used to record user revenue and expenditure details String details="Revenue and expenditure\t Account amount\t\t Revenue and expenditure amount\t\t explain\n"; int money; String info; //Initial amount int balance = 10000; while(isFlag) {//You can also write true System.out.println("---------------Household income and expenditure accounting software----------------\n"); System.out.println(" 1 Revenue and expenditure details"); System.out.println(" 2 Registered income"); System.out.println(" 3 Registered expenditure"); System.out.println(" 4 sign out\n"); System.out.print(" <Please enter 1-4>:"); char selection = Utility.readMenuSelection(); switch(selection) { case '1': System.out.println("---------------Current revenue and expenditure details record----------------"); System.out.println(details); System.out.println("----------------------------------------------"); break; case '2': System.out.print("Current revenue amount:"); money = Utility.readNumber(); System.out.print("Description of this income:"); info = Utility.readString(); balance += money; //Processing details details += "income\t" + balance + "\t\t" + money + "\t\t" + info + "\n"; System.out.println("-------------------Registration completed--------------------"); break; case '3': System.out.print("Current expenditure amount:"); money = Utility.readNumber(); System.out.print("Description of this expenditure:"); info = Utility.readString(); //Processing balance if(balance >= money) { balance -= money; //Processing details details += "expenditure\t" + balance + "\t\t" + money + "\t\t" + info + "\n"; }else { System.out.println("Wrong! Account limit exceeded!"); } System.out.println("-------------------Registration completed--------------------"); break; case '4': System.out.println("Confirm whether to exit(Y/N):"); char isExit = Utility.readConfirmSelection(); if(isExit == 'Y') { isFlag = false;//You can also break; } break; } } }
Utility.java
package test03; import java.util.*; /*Utility Tools: Encapsulate different functions into methods */ public class Utility{ private static Scanner scanner = new Scanner(System.in); /*Used for interface selection. This method reads the keyboard. If the user enters any character from 1 to 4, the return value of the method is any character entered */ public static char readMenuSelection(){ char c; for(;;){ String str = readKeyBoard(1); c = str.charAt(0); if (c !='1' && c !='2' && c != '3' && c != '4'){ System.out.print("Selection error, please re-enter"); }else break; } return c; } /* It is used for the input of expenditure and income amount. It reads an integer with a length of no more than 4 digits and takes it as the return value of the method */ public static int readNumber(){ int n; for(;;){ String str = readKeyBoard(4); try{ n = Integer.parseInt(str); break; }catch(NumberFormatException e){ System.out.print("Error in digital input, please re-enter:"); } } return n; } /*Input for expense and income description. It is used to read the input value with a string length of no more than 8 entered from the keyboard, And take it as the return value of the method */ public static String readString(){ String str = readKeyBoard(8); return str; } /*Used to confirm the selected input, read 'y' or 'n' from the keyboard and take it as the return value */ public static char readConfirmSelection(){ char c; for(;;){ String str = readKeyBoard(1).toUpperCase(); c = str.charAt(0); if(c == 'Y' || c == 'N'){ break; }else{ System.out.print("Selection error, please re-enter:"); } } return c; } private static String readKeyBoard(int limit){ String line = ""; while (scanner.hasNext()){ line = scanner.nextLine(); if (line.length()<1 || line.length()>limit){ System.out.print("Input length(Not greater than" + limit+ ")Error, please re-enter"); continue; } break; } return line; } }
5.3,Eclipse
Previous versions were alphabetical
Later changed to year
Reset when the view is messy
Don't forget naming conventions