1. Sequential structure
The sequential structure is relatively simple. For example, the code we wrote before is a sequential structure, which is executed line by line in the order of code writing
If you adjust the writing order of the code, the execution order also changes
2. Branch structure
2.1 if statement
Basic grammatical form 1
if(Boolean expression){ //Execute code when conditions are met }
Basic grammatical form 2
if(Boolean expression){ //Execute code when conditions are met }else{ //Execute code when conditions are not met }
Basic grammatical form 3 multi branch case
if(Boolean expression){ //Execute code when conditions are met }else if(Boolean expression){ //Execute code when conditions are met }else{ //Execute code when none of the conditions are met }
2.2 switch statement
Basic grammar
switch(integer|enumeration|character|character string){ case Content 1 : { Execute statement when content is satisfied; [break;] } case Content 2 : { Execute statement when content is satisfied; [break;] } ... default:{ Execute the statement when the content is not satisfied; [break;] } }
Note 1: depending on the value of the switch, the corresponding case statement will be executed. The case statement will end when a break is encountered. If the value in the switch does not match the case, the statement in default will be executed
We suggest that a switch statement should preferably carry default
Note 2 do not omit break, otherwise the effect of "multi branch selection" will be lost
int day = 1; switch(day) { case 1: System.out.println("Monday"); // break; case 2: System.out.println("Tuesday"); break; } // Operation results Monday Tuesday
We find that when we don't write break, the case statements will be executed downward in turn, thus losing the effect of multiple branches
Note 3 the type of value in switch can only be byte, int, short, char, string and enumeration.
double num = 1.0; switch(num) { case 1.0: System.out.println("hehe"); break; case 2.0: System.out.println("haha"); break; } // Compilation error Test.java:4: error: Incompatible types: from double Convert to int There may be losses switch(num) { ^ 1 Errors
Note 4 switch cannot express complex conditions
// For example, if the value of num is between 10 and 20, print hehe // Such code is easy to express using if, but it cannot be expressed using switch if (num > 10 && num < 20) { System.out.println("hehe"); }
Note 5 although switch supports nesting, it is ugly~
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 standard. After all, this is the face world
3. Circulation structure
3.1 while loop
Basic syntax format:
while(Cycle condition){ Circular statement; }
If the loop condition is true, the loop statement is executed; Otherwise end the cycle
matters needing attention
- Similar to if, the statement under while may not write {}, but only one statement can be supported when it is not written. It is recommended to add {}
- Similar to if, the {suggestion after while is written on the same line as while
- Similar to if, do not write more semicolons after while, otherwise the loop may not execute correctly
3.2 break
The function of break is to end the cycle ahead of time
Code example: find the multiple of the first 3 in 100 - 200
int num = 100; while (num <= 200) { if (num % 3 == 0) { System.out.println("A multiple of 3 was found, by:" + num); break; } num++; } // results of enforcement A multiple of 3 was found, by:102
Executing break will end the loop
3.3 continue
The function of continue is to skip this cycle and immediately enter the next cycle
Code example: find multiples of all 3 in 100 - 200
int num = 100; while (num <= 200) { if (num % 3 != 0) { num++; // Don't forget the + + here! Otherwise it will loop continue; } System.out.println("A multiple of 3 was found, by:" + num); num++; }
When the continue statement is executed, it will immediately enter the next cycle (determine the cycle conditions), so it will not execute the following print statement
3.4 for loop
Basic grammar
for(Expression 1;Expression 2;Expression 3){ Circulatory body; }
- Expression 1: used to initialize a loop variable
- Expression 2: loop condition
- Expression 3: update loop variable
Compared with the while loop, the for loop combines these three parts and is not easy to miss when writing code
Precautions (similar to while loop)
- Similar to if, the statement below for can not write {}, but only one statement can be supported when it is not written. It is recommended to add {}
- Similar to if, the {suggestion after for is written on the same line as while
- Similar to if, do not write more semicolons after for, otherwise the loop may not execute correctly
3.5 do while loop (optional)
Basic grammar
do{ Circular statement; }while(Cycle condition);
Execute the loop statement first, and then determine the loop condition
Code example: print 1 - 10
int num = 1; do { System.out.println(num); num++; } while (num <= 10)
matters needing attention
- Don't forget the semicolon at the end of the do while loop
- Generally, do while is rarely used, and for and while are recommended
4. Input and output
4.1 output to console
Basic grammar
System.out.println(msg); // Output a string with newline System.out.print(msg); // Output a string without line breaks System.out.printf(format, msg); // Format output
- println output content comes with \ n, print does not \ n
- The format output mode of printf is basically the same as that of C language
format string
4.2 input from keyboard
Read in a character (optional)
A character can be read directly using System.in.read, but it needs to be combined with exception handling (which will be highlighted later)
System.out.print("Enter a Char:"); char i = (char) System.in.read(); System.out.println("your char is :"+i); // Compilation error Test.java:4: error: Unreported exception error IOException; It must be captured or declared in order to be thrown char i = (char) System.in.read(); ^ 1 Errors
Correct writing
import java.io.IOException; // IOException package needs to be imported try { System.out.print("Enter a Char:"); char i = (char) System.in.read(); System.out.println("your char is :"+i); } catch (IOException e) { System.out.println("exception"); }
This method is troublesome and we don't recommend it
Use Scanner to read string / integer / floating point number
import java.util.Scanner; // The util package needs to be imported Scanner sc = new Scanner(System.in); System.out.println("Please enter your name:"); String name = sc.nextLine(); System.out.println("Please enter your age:"); int age = sc.nextInt(); System.out.println("Please enter your salary:"); float salary = sc.nextFloat(); System.out.println("Your information is as follows:"); System.out.println("full name: "+name+"\n"+"Age:"+age+"\n"+"Salary:"+salary); sc.close(); // Note that remember to call the close method // results of enforcement Please enter your name: Zhang San Please enter your age: 18 Please enter your salary: 1000 Your information is as follows: full name: Zhang San Age: 18 Salary: 1000.0
Use the Scanner loop to read N numbers
Scanner sc = new Scanner(System.in); double sum = 0.0; int num = 0; while (sc.hasNextDouble()) { double tmp = sc.nextDouble(); sum += tmp; num++; } System.out.println("sum = " + sum); System.out.println("avg = " + sum / num); sc.close(); // results of enforcement 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
5. Number guessing game
Rules of the game:
The system automatically generates a random integer (1-100), and then the user enters a guessing number. If the entered number is smaller than the random number, it will prompt "low". If the entered number is larger than the random number, it will prompt "high". If the entered number is equal to the random number, it will prompt "guessed right"
Reference code
import java.util.Random; import java.util.Scanner; class Test { public static void main(String[] args) { Random random = new Random(); // The default random seed is system time Scanner sc = new Scanner(System.in); int toGuess = random.nextInt(100); // System.out.println("toGuess: " + toGuess); while (true) { System.out.println("Please enter the number you want to enter: (1-100)"); int num = sc.nextInt(); if (num < toGuess) { System.out.println("Low"); } else if (num > toGuess) { System.out.println("High"); } else { System.out.println("You guessed right"); break; } } sc.close(); } }