Typeora copy images to: screenshots from notes
It is only used as a record of knowledge points in the process of Java learning
To be updated...
Cha_03 control statement
3.1 selection of structure
3.1.1 if statement (branch statement)
if statements are branch statements, also known as conditional statements.
1. Grammatical structure
(1) if structure
if(Boolean expression){ Java sentence; Java sentence; }
(2) If else structure
if(Boolean expression){ Java Statement 1; }else{ Java Statement 2; } //If the expression value is true, execute statement 1, otherwise execute statement 2
(3) If else structure
if(Boolean expression 1){ Java Statement 1;//When the value of expression 1 is true, execute statement 1; Otherwise, judge expression 2 }else if(Boolean expression 2){ Java Statement 2;//When the value of expression 2 is true, execute statement 2; Otherwise, judge expression 3 }else if(Boolean expression 3){ Java Statement 3;//When the value of expression 3 is true, execute statement 3; Otherwise, it will not be executed }
(3) If else structure
if(Boolean expression 1){ Java Statement 1;//When the value of expression 1 is true, execute statement 1; Otherwise, judge expression 2 }else if(Boolean expression 2){ Java Statement 2;//When the value of expression 2 is true, execute statement 2; Otherwise, judge expression 3 }else if(Boolean expression 3) ··· else{ Java sentence n;//When the values of the previous expressions are false, execute the statement n; }
- When there is only one statement in each branch, the curly bracket "{}" can be omitted.
- Control statements and control statements can be nested.
2. Code example
Activities at Lake LazyDays
Your job at Lake LazyDays resort is to provide activity suggestions to guests according to weather conditions. Here is a list of activities:
temp >= 80: swimming;
60 <= temp < 80: tennis;
40 <= temp < 60: golf;
temp < 40: skiing.
1. Write a program to prompt the user to enter an air temperature value, and then print out the activities suitable for the air temperature. Tip: use if else statements and make sure your condition settings don't have to be too complicated.
2. Modify the program to print "Visit our shops!" when temp > 95 or temp < 20. Tip: use Boolean operators in conditional expressions.
import java.util.Scanner; public class LazyDays{ public static void main(String[] args){ //Create a Scanner object scan to obtain the data entered by the user from the keyboard Scanner scan = new Scanner(System.in); //Declare an int variable temp int temp; while (scan.hasNextInt( )) { //Prompt the user to enter today's temperature System.out.println("Please enter today's temperature:"); //Assign the temperature entered by the user to temp temp = scan.nextInt( ); //Use the if statement to judge the temperature of the day, and output different play suggestions according to different temperatures if (temp > 95 || temp < 20) { //When the temperature temp is higher than 95 or lower than 20, the output "visit our HOOPS!" System.out.println("Visit our shops!"); } else if (temp >= 80) { //When the temperature temp is not lower than 80, output "swimming" System.out.println("swimming"); } else if (60 <= temp && temp < 80) { //If temp is not lower than 60, output "tennis" System.out.println("tennis"); } else if (40 <= temp && temp < 60) { //If temp is not lower than 60, "golf" is output; otherwise, "skiing" is output System.out.println("golf"); } else { //If the above conditions are not met, "skiing" is output System.out.println("skiing"); } } scan.close( ); } }
3.1.2 switch statement
1. Syntax format
switch (expression){ case Value 1: Statement block 1; break;//Break the current switch statement //When the value of the expression is value 2 or value 3, statement block 2 is executed case Value 2: case Value 3: Statement block 2; break; case ···: //When the value of the above case statement is not equal to the value of the expression, execute the false statement default: Statement block n; }
be careful:
(1) switch statements can have multiple case statements;
(2) The value of the expression can be integer or String (cahr, byte, int, short, boolean, String) or the corresponding packing type;
(3) When the value of the expression is equal to the value of case, execute the statement block of the case branch and continue until the end of the first break;
(4) If there is no break statement, the program continues to execute until the end of the first break, or until the end of the default branch.
(5) A switch can contain zero or one default statement. Generally, the default statement is placed last.
2. Code example
Convert the English level of students into Chinese level classification: A is excellent, B and C are good, D is passed and F is failed. If the level is no longer within this range, it will be prompted to go beyond the range.
import java.util.Scanner; public class Grade { public static void main ( String [ ] args ) { // Create a Scanner object scan to obtain the data entered by the user from the keyboard Scanner scan = new Scanner(System.in); // Declare a String variable grade. String grade; while (scan.hasNext( )) { // Prompts the user for a hierarchy System.out.println("Please enter your grade:"); // Assign the English grade of the entered student grade to grade grade = scan.next( ); // Use the switch statement to output different play suggestions according to different temperatures switch (grade) { case "A" : System.out.println("excellent"); break; case "B" : case "C" : System.out.println("good"); break; case "D" : System.out.println("pass"); break; case "F" : System.out.println("Fail"); break; default : System.out.println("be not in A~F In range!"); } } scan.close( ); } }
3.1.3 comprehensive example of structure selection
1. Title
Rock, Paper, Scissors
Program rock Java is a framework of stone scissors cloth game. Save the program to the local directory and supplement the program statement according to the prompt. The program allows users to input a project, the computer randomly generates a project, compares the two projects, and gives the winning and losing results. For example, a program might run as follows:
Users can enter R, P, s or R, P, s to represent three items: stone, cloth and scissors. The items entered by the user are saved in string variables to facilitate case conversion.
Use a switch statement to convert a random integer into an item given by the computer in the game.
In many cases, the program needs to generate a Random number in a certain range. The Random class in the Java class library provides programmers with such a function, which can generate a series of Random numbers at the same time. The following variables declare a variable generator of Random type and are initialized with the new operator:
Random generator = new Random();
The generator object can generate integer or floating-point random numbers. You need to use the nextInt method or nextFloat method. nextInt() returns an arbitrary integer random number, and nextInt(n) returns a random integer between 0 and n-1. nextFloat() and nextDouble() return a floating-point number between 0 and 1.
Assuming that you need to generate an integer between 30 and 99, you can use the following method:
- Use nextint(): math abs(generator.nextInt())%70 + 30;
- Use nextint (70): generator nextInt(70)+30;
- Use nexFloat: (int)(generator.nextFloat()*70) + 30
Adding 30 means that it starts from 30 to 99 and takes random values in 100 numbers. Random numbers start from 0 by default.
Complete the following procedure. This program is used to generate random numbers. Note that you need to put Java util. Random class importer.
2. Code
import java.util.Scanner; import java.util.Random; public class Rock{ public static void main(String[] args){ //Declare variable String personPlay;//Represents the value entered by the user String computerPlay = "";//Represents the value given by the computer int randomInt;//random number //create object Scanner scan = new Scanner(System.in); Random random = new Random(); //Prompts the user for stone, scissors, or cloth System.out.print("Enter your play: (R, P or S): "); //Start the game while(scan.hasNext()){ personPlay = scan.next().toUpperCase(); randomInt = random.nextInt(3); switch(randomInt){ case 0: computerPlay = "R"; break; case 1: computerPlay = "S"; break; case 2: computerPlay = "P"; break; } if(personPlay.equals(computerPlay)){ System.out.println("It's a tie."); }else if(personPlay.equals("R")){ if(computerPlay.equals("P")){ System.out.println("Paper covered stone.\n" + "Compueter wins, you failed!"); }else{ System.out.println("Rock crushes scissors.\n" + "You win!"); } }else if(personPlay.equals("S")){ if(computerPlay.equals("R")){ System.out.println("Rock crushes scissors.\n" + "Compueter wins, you failed!"); }else{ System.out.println("Sissors cut paper.\n" + "You win!"); } }else if(personPlay.equals("P")){ if(computerPlay.equals("S")){ System.out.println("Sissors cut paper.\n" + "Compueter wins, you failed!"); }else{ System.out.println("Paper covered stone.\n" + "You win!"); } }else if(personPlay.equals("E")){ //game over System.out.println("Game over! \n" + "Thank for playing!"); return; }else { //Judge the user's input error and prompt to re-enter the correct characters System.out.println("Error! Please enter: \"R\", \"S\" or \"P\"."); } System.out.print("\nEnter your play: (R, P or S): "); } scan.close(); } }
3. Program running results
3.2 circular statements
3.2.1 while cycle
1. Syntax format
while(Boolean expression){ Statement block; }
When the loop condition of while is satisfied, the statement block in while is executed. Similarly, "{}" can not be added when there is only one statement. In order to facilitate reading, it is recommended to add "{}".
2. Code example
3.2.2 do while cycle
1. Syntax format
do{ Statement block; }while(Cycle condition);
be careful:
- Whether the while loop condition is satisfied or not, execute the do statement block first, and then judge whether the expression meets the while condition.
- The do while loop executes the loop at least once. When the conditions are met, the structure of the do while loop is the same as that of the while loop.
- In a do while loop, while is followed by a semicolon
Program trap:
double num = 1.0;
while(num!= 0.0){
System.out.println(num);
num -= 0.1;
}
Note: num is a floating-point variable, and the precision will be lost when performing four operations directly. Therefore, the above program will enter an dead cycle. To solve this problem, you can give a deviation value.
2. Code example
Example of program running results:
3.2.3 for loop
1. Syntax format
for(Initial value;Conditional expression;increment){ Statement block; }
be careful:
- In the for loop, the initial value is assigned only once;
- When the conditional expression is satisfied, execute the statement block and add value, and then re judge whether the for loop condition is satisfied.
2. Code example
Chicken and rabbit in the same cage. There are several rabbits and chickens in a cage, with 10 heads and 32 feet. Find the number of rabbits and chickens.
package ForTest; public class ChookRabbit{ public static void main(String[] args){ int head = 10; int feet = 32; int sumRabbit; int sumChook; for(sumChook = 0; sumChook < 16; sumChook++){ //The total number of chickens and rabbits is 10 sumRabbit = head - sumChook; //The chicken has two feet and the rabbit has four feet, a total of 32 feet if(sumRabbit * 4 + sumChook * 2 == feet){ System.out.println("There are " + sumRabbit + " rabbits and " + sumChook + " chooks in the cage."); } } } }
Program running results:
3.2.4 for each cycle
1. Syntax format
for(Type variable: Array or collection){ Statement block }
be careful:
(1) For each loop is also called "enhanced for loop". It is proposed to simplify the iterative process of collection classes, enumerations and arrays.
(2) There are two control elements in parentheses after the keyword for, separated by ":. Before the colon is the variable and its type. The variable here is also called iterator, which is assigned repeatedly in the loop body; After the colon is the array or collection to be traversed. It is required that the type of variable should be consistent with the element type in the array or collection to be traversed.
2. Code example
Example of program running results:
3.2.5 comprehensive examples of circular statements
1. Title
Factorials
Factorial of n (n!) Represents the product of integers from 1 to n. For example, 4= 123*4=24. Also, 0= 1. Factorial does not apply to negative numbers.
1. Write a program, ask the user to enter a non negative integer, and then print the factorial of the integer. Use the while loop statement to write the program. Consider the user entering 0.
2. Modify the program to check whether the user enters a non negative integer. If you enter a negative number, you will be prompted to enter a non negative integer, and you will be asked to re-enter it until you enter a non negative integer.
2. Code
import java.util.Scanner; public class Factorials{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n; int factories; System.out.println("Please enter a number:"); while(scan.hasNext()){ n = scan.nextInt(); factories = 1; if(n<0){ //Negative numbers have no class System.out.println("Error!"); }else if(n == 0){ //0! = 1 System.out.println(n + "! = 1"); }else{ //Output format n= 1 * 2 * ··· * n = ··· System.out.print(n + "! = 1"); for(int i = 1; i <= n; i++){ //Computational hierarchy factories *= i; if(i > 1){ System.out.print(" * " + i); } } //Output the final result and wrap System.out.print(" = " + factories + "\n"); } //Prompt the user for a number System.out.println("Please enter a number:"); } scan.close(); } }
3. Program running results
3.3 interrupt statement
Interrupt statements in Java include return, break and continue, which are used to execute the end of the loop
3.3.1 return statement
return statement