Java process control
-
User interaction Scanner
-
Sequential structure
-
Select structure
-
Cyclic structure
-
break & continue
-
practice
Scanner object
-
The basic syntax we learned before does not realize the interaction between programs and people, but Java provides us with such a tool class that we can obtain user input. java.util.Scanner is a new feature of Java 5. We can get user input through scanner class.
-
Basic syntax: Scanner s = new Scanner (System.in);
-
Get the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to judge whether there is still input data.
-
next():
-
Be sure to read valid characters before you can end the input.
-
The next() method will automatically remove the whitespace encountered before entering valid characters.
-
Only after entering a valid character will the blank space entered after it be used as a separator or terminator.
-
next() cannot get a string with spaces.
-
package com.practice.Scanner; import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scanner object to accept keyboard data Scanner scanner = new Scanner(System.in); System.out.println("use next Accepted by:"); //Judge whether the user has entered a string if (scanner.hasNext()) { //Accept using next String str = scanner.next(); System.out.println("The input content is:"+str); } //All classes belonging to IO streams will always occupy resources if they are not closed. Close them in time scanner.close(); } }
-
nextLine():
-
Take Enter as the ending character, that is, the nextLine() method returns all characters before entering carriage return.
-
You can get blank.
-
package com.practice.Scanner; import java.util.Scanner; public class Demo02 { public static void main(String[] args) { //Receive data from keyboard Scanner scanner = new Scanner(System.in); System.out.println("use next Mode acceptance:"); //Determine whether there is any input if (scanner.hasNextLine()) { String str = scanner.nextLine(); System.out.println("The input content is:"+str); } scanner.close(); } }
Sequential structure
-
The basic structure of JAVA is sequential structure. Unless otherwise specified, it will be executed sentence by sentence in order.
-
Sequential structure is the simplest algorithm structure.
-
Between statements and between boxes, it is carried out in the order from bottom to top. It is composed of several processing steps executed in turn. It is a basic algorithm structure that any algorithm is inseparable from.
Select structure
-
if single selection structure
-
if double selection structure
-
if multiple selection structure
-
Nested if structure
-
switch multiple selection structure
if single selection structure
-
By judging whether something is feasible and then executing it, such a process is represented by an if statement
-
Syntax:
if(expression){ //The statement that will be executed if the Boolean expression is true }
if double selection structure
-
When the requirement cannot be solved with an if, there need to be two judgments and a double selection structure, so there is an if else structure.
-
Syntax:
if(Boolean expression){ //If the Boolean expression has a value of true }else{ //If the value of the Boolean expression is false }
if multiple selection structure
-
Since there are many choices in real life, a multi-choice structure is needed to deal with them.
-
Syntax:
if(Boolean expression 1){ //If the value of Boolean expression 1 is true, execute the code }else if(Boolean expression 2){ //If the value of Boolean expression 2 is true, execute the code }else if(Boolean expression 3){ //If the value of Boolean expression 3 is true, execute the code }else{ //If none of the above Boolean expressions is true, execute the code }
code
package com.practice.struct; import java.util.Scanner; public class IfDemo02 { public static void main(String[] args) { //If the test score is greater than 60, you will pass, and if it is less than 60, you will fail Scanner scanner = new Scanner(System.in); System.out.println("Please enter your grade:"); double score = scanner.nextDouble(); if (score == 100) { System.out.println("Congratulations, full marks"); } else if (score < 100 && score >= 90) { System.out.println("A level"); } else if (score < 90 && score >= 80) { System.out.println("B level"); } else if (score < 80 && score >= 70) { System.out.println("C level"); } else if (score < 70 && score >= 60) { System.out.println("D level"); } else if (score < 60 && score >= 0) { System.out.println("fail,"); } else { System.out.println("Please enter the correct score"); } scanner.close(); } }
Nested if statements
Syntax:
if(Boolean expression 1){ //If the value of Boolean expression 1 is true, execute the code if(Boolean expression 2){ //If the value of Boolean expression 2 is true, execute the code } }
switch multiple selection structure
-
One implementation of the multiple selection structure is the switch case statement.
-
The switch case statement determines whether a variable is equal to a value in a series of values. Each value is called a branch.
-
The variable types in the switch statement can be:
-
byte, short, int or char
-
Start with Java SE7
-
switch supports String type
-
At the same time, the case label must be a string constant or an argument
-
switch(expression){ case value: //sentence break;//Optional case value: //sentence break;//Optional //You can use any number of case statements default://Optional //sentence }
code
package com.practice.struct; public class SwitchDemo02 { public static void main(String[] args) { String name = "Zhang"; //A new feature of JDK7, the expression result can be a string //Decompile Java -- class (bytecode file) - (decompile) IDEA switch (name){ case "Lee": System.out.println("Lee"); break; case "Zhang": System.out.println("Zhang"); break; default: System.out.println("Hello"); } } }
Decompile code
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package com.practice.struct; public class SwitchDemo02 { public SwitchDemo02() { } public static void main(String[] args) { String name = "Zhang"; byte var3 = -1; switch(name.hashCode()) { case 24352: if (name.equals("Zhang")) { var3 = 1; } break; case 26446: if (name.equals("Lee")) { var3 = 0; } } switch(var3) { case 0: System.out.println("Lee"); break; case 1: System.out.println("Zhang"); break; default: System.out.println("Hello"); } } }
Cyclic structure
-
while Loop
-
do...while
-
for loop
-
In Java 5, an enhanced for loop is introduced, which is mainly used for arrays
while Loop
-
while is the most basic loop. Its structure is:
while(Boolean expression){ //Cyclic content }
-
As long as the Boolean expression is true, the loop will continue to execute.
-
In most cases, it will stop the loop. You need a way to invalidate the expression to end the loop.
-
In the case of less unsealing, the loop needs to be executed all the time, such as the server's request response listening, etc.
-
If the loop condition is always true, it will cause infinite non loop [dead loop]. In normal business programming, dead loop should be avoided as far as possible. It will affect the program performance or cause the program to get stuck and crash!
do... while loop
-
For the while statement, if the condition is not met, it cannot enter the loop. But sometimes it is executed at least once even if the conditions are not met.
-
The do... While loop is similar to the while loop, except that the do... While loop is executed at least once.
do{ //Code statement }while(Boolean expression);
-
Difference between while and do while:
-
While is judged before execution. Do while is to execute first and then judge!
-
Do... while always ensures that the loop is executed at least once!
-
for loop
-
Although all loop structures can be represented by while or do... While, Java provides another statement - for loop, which makes some loop structures simpler.
-
for loop statement is a general structure that supports iteration. It is the most effective / flexible loop structure.
-
The number of times the for loop is executed is determined before execution. The syntax format is as follows:
for(initialization; Boolean expression; to update){ //Code statement }
Code 1
package com.practice.struct; public class ForDemo01 { public static void main(String[] args) { //Exercise 1: calculate the sum of odd and even numbers between 0 and 100 int oddSum = 0; int evenSum = 0; for (int i = 0; i < 100; i++) { if (i%2!=0){ oddSum = oddSum + i; }else { evenSum = evenSum + i; } } System.out.println("Odd sum:" + oddSum); System.out.println("Even sum:" + evenSum); } }
Code 2
package com.practice.struct; //multiplication table public class ForDemo02 { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + "*" + i + "=" + (i*j) + "\t"); } System.out.println(); } } }
Enhanced for loop
-
Mainly for arrays
-
Java 5 introduces an enhanced for loop that is primarily used for arrays or collections
-
Java enhanced for loop syntax format:
for(Declaration statements: expressions){ //Code sentence }
-
Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time.
-
Expression: an expression is the name of the array to be accessed, or a method whose return value is an array.
break continue
-
Break in the body of any loop statement, you can use break to control the flow of the loop. Break is used to forcibly exit the loop without executing the remaining statements in the loop. (break statements are also used in switch statements)
package com.practice.struct; public class BreakDemo { public static void main(String[] args) { int i = 0; while (i < 100) { i++; System.out.println(i); if (i == 30){ break;//Jump out of this cycle } System.out.println(i); } } }
-
The continue statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time.
package com.practice.struct; public class ContinueDemo { public static void main(String[] args) { int i = 0; while (i<100){ i++; if (i%10==0){ System.out.println(); continue;//Jump out of values in all conditions } System.out.println(i); } /* * break In the body of any loop statement, you can use break to control the flow of the loop. *break Used to forcibly exit the loop without executing the remaining statements in the loop. (break statements are also used in switch statements) * continue Statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time. * */ } }
-
About goto keyword
-
Goto keyword has long appeared in programming language. Although goto is still a reserved word of Java, it has not been officially used in the language; Java does not have goto. However, we can still see the shadow of goto in the two keywords break and continue... Labeled break and continue.
-
"label" refers to the identifier followed by a colon, for example: label:
-
For Java, the only place where tags are used is before loop statements. The only reason to set the label before the loop is that you want to nest another loop in it. Because the break and Continue keywords usually only break the current loop, but if they are used with the label, they will break to the place where the label exists.
-
package com.practice.struct; public class LabelDemo { public static void main(String[] args) { //Print all indexes between 101 and 150 //Prime number refers to a natural number that has no other factors except 1 and itself among natural numbers greater than 1. int count = 0; outer:for (int i = 101; i < 150; i++) { for (int j = 2; j < i/2;j++){ if (i % j == 0) { continue outer; } } System.out.println(i+""); } } }
code
package com.practice.struct; public class TestDemo { public static void main(String[] args) { //Print 5 rows of triangles for (int i = 1; i <= 5; i++) { for (int j = 5; j >=i; j--){ System.out.print(" "); } for (int j = 1; j <= i; j++){ System.out.print("*"); } for (int j = 1; j < i; j++){ System.out.print("*"); } System.out.println(); } } }
explain
Perform the initialization step first. You can declare a type, but you can initialize one or more loop control variables or empty statements.
Then, the value of the Boolean expression is detected. If true, the loop body is executed. If false, the loop terminates and begins to execute the statements following the loop.
After executing a loop, update the loop control variable (the iteration factor controls the increase or decrease of the loop variable).
Detect the Boolean expression again. Loop through the above procedure.