1, Overview
- The process control during program running depends on how the program is executed. There are three process control statements, namely sequence control, branch control and loop control.
2, Sequential control
- 1. The program is executed line by line from top to bottom without any judgment and jump
- 2. Precautions
When defining variables in Java, legal forward references are used, that is, variables are defined before they are used.
int n1 = 12; int n2 = n1 + 1; //Absolutely int n2 = n1 + 1; int n1 = 12; //That won't work
3, Branch control
1. Single branch if
-
(1) Syntax:
if(Conditional expression){ Execute code block;There can be multiple statements }
-
(2) Note: when the conditional expression is true, the code in {} will be executed; otherwise, the code in {} will not be executed;
If there is only one piece of data in the execution code block, {} can be omitted, but it is recommended to write it -
(3) For example, write a program and input your age. If you are older than 18, you will output "your age is older than 18, you should be responsible for your behavior, and you can go to jail."
Train of thought analysis:1,Receive input age, one Scanner object 2,Save age to a variable 3,use if Judge and output the corresponding message Scanner scanner = new Scanner(System.in); System.out.println("Please enter your age"); int age = scanner.nextInt(); if(age>14){ System.out.println("You are over 18 years old. You should be responsible for your actions and can go to jail"); } //output //Please enter your age //21 //You are over 14 years old. You should be responsible for your actions and can go to jail
2. Double branch if else
-
(1) Syntax:
if(Conditional expression){ Execute code block 1;(There can be multiple statements) }else{ Execute code block 2;(There can be multiple statements) }
-
(2) Explain
When the conditional expression is true, the code in {execute code block 1} will be executed; otherwise, the code in {execute code block 2} will be executed;
If there is only one piece of data in the execution code block, {} can be omitted, but it is recommended to write it -
(3) For example, write a program and input your age. If you are older than 18, you will output "your age is older than 18, you should be responsible for your behavior, and you can go to jail". Otherwise, you will output "you are still young, and you will be let go this time"
Train of thought analysis:1,Receive input age, one Scanner object 2,Save age to a variable 3,use if Judge and output the corresponding message Scanner scanner = new Scanner(System.in); System.out.println("Please enter your age"); int age = scanner.nextInt(); if(age>18){ System.out.println("You are over 18 years old. You should be responsible for your actions and can go to jail"); }else{ System.out.println("You're still young. I'll let you go this time"); } //output //Please enter your age //16 //You're still young. I'll let you go this time
-
(4) Related exercise 1: read the program and write the final output
int x = 7; int y = 4; if(x > 5){ //Correct, enter this code block if(y > 5){ //Error, this code block will not be executed, //Instead, it will enter the code block of else corresponding to this if System.out.println(x + y); }else{ System.out.println("study Java"); //So this statement will be output } }else{ System.out.println("x = " + x); } //Output learning Java
-
(5) Related exercise 2: write a program: declare two double variables and assign values. If the first number is less than 10 and the second number is less than 20, print the sum of the two numbers
Train of thought analysis:1,Receive input data, one Scanner object 2,Save the input data to a double Type variable 3,use if Judge and output the corresponding message Scanner scanner = new Scanner(System.in); System.out.println("Please enter the first number " ); double d1 = scanner.nextDouble(); System.out.println("Please enter the second number " ); double d2 = scanner.nextDouble(); if(d1 > 10.0 && d2 <20 ){ System.out.println("The sum of the two numbers entered is" + (d1 + d2) ); } //output //Please enter the first number //15 //Please enter the second number //15 //The sum of the two numbers entered is 30.0
-
(6) Related exercise 3: write a program: define two variables of type int, judge whether the sum of the two can be divided by 3 and 5, and print the result
Train of thought analysis:1,Receive input data, one Scanner object 2,Save the input data to a int Type variable 3,use if Judge and output the corresponding message Scanner scanner = new Scanner(System.in); System.out.println("Please enter the first number" ); int n1 = scanner.nextInt(); System.out.println("Please enter the second number" ); int n2 = scanner.nextInt(); int sum = n1 + n2; if(sum % 3 == 0 && sum % 5 == 0){ System.out.println("The sum of the two numbers entered is" + (n1 + n2) + "\n Can be divided by 3 and 5" ); }else{ System.out.println("The sum of the two numbers entered is" + (n1 + n2) + "\n Cannot be divided by 3 and 5" ); } //output //Please enter the first number //6 //Please enter the second number //9 //The sum of the two numbers entered is 15 //Can be divided by 3 and 5
-
(7) Related exercise 4: write a program: judge whether a year is a leap year. Judgment condition 1: the year can be divided by 4, but not by 100, and 2: it can be divided by 400
Train of thought analysis:1,Receive input data, one Scanner object 2,Save the input data to a int Type variable 3,use if Judge and output the corresponding message Scanner scanner = new Scanner(System.in); System.out.println("Please enter a number" ); int n1 = scanner.nextInt(); if((n1 % 4 == 0 && n1 % 100 != 0) || n1 % 400 == 0){ System.out.println("The year entered is a leap year" ); }else{ System.out.println("The year entered is not a leap year" ); } //output //Please enter the first number //2000 //The year entered is a leap year
3. Multi branch
-
(1) Syntax:
if(Conditional expression 1){ Execute code block 1;(There can be multiple statements) }else if(Conditional expression 2){ Execute code block 2;(There can be multiple statements) } else if(Conditional expression 3){ Execute code block 3;(There can be multiple statements) } ...... else{ //Multiple branches may not have this last else. If all conditional expressions are not true, there is no execution entry Execute code block n //If there is this else, if all conditional expressions are not true, the code block in this else will be executed by default }
-
(2) Explain
When the conditional expression 1 is true, the code in {execute code block 1} will be executed,
If conditional expression 1 is not true, it will judge whether conditional expression 2 is true. If conditional expression 2 is true, execute the code in {execute code block 2};
If conditional expression 2 is not true, it will judge whether conditional expression 3 is true;
By analogy, if all expressions fail, execute the else code block. Note that there can only be one execution entry -
(3) For example: write a program, input sesame credit score, and display the corresponding results;
If:
If the credit is divided into 100, the output credit is excellent
If the credit is divided into (80,99], the output credit is good
If the credit is divided into (60,80], the output credit is general
In other cases, the output credit failsTrain of thought analysis:1,Receive input scores, one Scanner object 2,Save the score to a variable 3,use if - else Multi branch judgment, output corresponding message Scanner scanner = new Scanner(System.in); System.out.println("Please enter your sesame credit score" ); int n1 = scanner.nextInt(); if(n1 >= 1 && n1 <=100){ //This can be done using an exception handling mechanism if(n1 == 100){ System.out.println("Excellent credit" ); }else if(n1 > 80 && n1 <= 99){ System.out.println("Good credit" ); }else if(n1 >=60 && n1 <= 80){ System.out.println("General credit" ); }else{ System.out.println("Credit failure" ); } }else{ System.out.println("The credit score entered must be within 1 ~ 100" ); } //output //Please enter your sesame credit score //97 //Good credit
4. Nested branch
-
(1) Basic introduction:
Another complete branch structure is completely nested in one branch structure. The inner branch structure is called inner branch, and the outer branch structure is called outer branch.Writing standard: no more than three layers to ensure the readability of the code
-
(2) Syntax:
if(Conditional expression 1){ if(Conditional expression 2){ Execute code block 2;(There can be multiple statements) } else if(Conditional expression 3){ Execute code block 3;(There can be multiple statements) } }else{ ..... }
-
(3) For example: write a program to display the corresponding results according to the input
If:
Participate in the singer competition. If the preliminary score is greater than 8.0, you will enter the final, otherwise you will be prompted to be eliminated
And enter the men's group or the women's group according to the gender prompt
Output performance and gender, judge and output informationTrain of thought analysis:1,Receive input information, one Scanner object 2,Save the information to variables separately 3,use if - else Judge multiple branches and nested branches and output corresponding messages First judge whether to enter the finals, and then judge whether it is the men's group or the women's group in the nesting of entering the finals Scanner scanner = new Scanner(System.in); System.out.println("Please enter your grade" ); double score = scanner.nextDouble(); if(score > 0.0){ if(score > 8.0){ System.out.println("You have reached the finals" ); System.out.println("Please enter your gender" ); char gender = scanner.next().charAt(0); if(gender == 'male' ){ System.out.println("You have entered the men's finals"); }else if(gender == 'female' ){ System.out.println("You have entered the women's group of the finals"); }else{ System.out.println("The gender you entered is incorrect. Please re-enter it" ); } }else{ System.out.println("You've been eliminated"); } }else{ System.out.println("The grade you entered is incorrect. Please re-enter it" ); } //output //Please enter your grade //9 //You have reached the finals //Please enter your gender //male //You have entered the men's finals
-
(4) After class exercise: write a ticket issuing system: print the ticket price according to the month and age in the off peak season
Train of thought analysis:1,Receive input information, one Scanner object 2,Save the information to variables separately 3,use if - else Judge multiple branches and nested branches and output corresponding messages First, judge the low season and peak season according to the input months, and then judge the ticket price according to the input in different month nesting Scanner scanner = new Scanner(System.in); System.out.println("Please enter the current month" ); int month = scanner.nextInt(); if(month >= 4 && month <= 10){ System.out.println("Please enter your age" ); int age = scanner.nextInt(); if(age >=18 && age <=60){ System.out.println("The fare you bought is 60 yuan" ); }else if(age < 18){ System.out.println("The fare you bought is: 30 yuan" ); }else if(age >60){ System.out.println("The fare you bought is 20 yuan" ); }else{ System.out.println("The age you entered is incorrect. Please re-enter it" ); } }else if((month > 10 && month <= 12) || (month > 0 && month <= 3)){ System.out.println("Please enter your age" ); int age = scanner.nextInt(); if(age >=18 && age <=60){ System.out.println("The fare you bought is 40 yuan" ); } }else { System.out.println("The month you entered is incorrect. Please re-enter it" ); } //output //Please enter the current month //8 //Please enter your age //40 //The fare you bought is 60 yuan
5. switch branch structure
-
(1) Grammar
switch(Conditional expression){ case Constant 1: Execute code block 1;(There can be multiple statements) break; case Constant 2: Execute code block 2;(There can be multiple statements) break; ..... case constant n: Execute code block n;(There can be multiple statements) break; default: default Execute code block; break; }
-
(2) Use details
1. Switch keyword, indicating the switch branch2. The expression corresponds to a value
3. case constant 1: when the value of the conditional expression is equal to constant 1, code block 1 is executed
4. break means to exit the switch
5. If the value of the conditional expression is not equal to the constant 1, continue to look down to see if there is a match. If there is another match, execute the corresponding code block
6. If none of them match, execute the code block in default
-
(3) Considerations and details discussion
1. The expression data type should be consistent with the constant type after case, or it can be automatically converted to a type that can be compared with each other. For example, the input is a character and the constant is int2. The return value of the expression in switch (expression) must be byte short int char enum (enumeration) String / / note that there is no floating point type
3. The value in the case clause must be a constant, not a variable, such as
char c1 = 'a'; char c2 = 'b'; switch(c1){ case c2: //This place will report an error. You can't use c2. Use 'b' System.out.println("OK"); break; }
4. The default clause is optional. If there is no matching case, execute default
5. The break statement is used to make the program jump out of the whole switch statement block after executing a case branch. If there is no break, the program will run down the switch until the end. This is word code block penetration
-
(4) Comparison between switch and if
1. If there are not many specific values to judge and the six data types of byte, short, int, char, enum and string are met, switch is recommended
2. For interval judgment, if is used when the result is boolean type judgment, and if is used in a wider range
-
(5) After class exercise ①: write a program that can receive one character, a,b,..., g, corresponding to seven days a week, and complete it through switch
Train of thought analysis:1,Receive input information, one Scanner object 2,Save the information to variables separately 3,use switch case To determine what corresponding message should be output Scanner scanner = new Scanner(System.in); System.out.println("Please enter a character a~ g"); char c = scanner.next().charAt(0); //In java, as long as there is a value, the return is an expression switch(c){ case 'a': System.out.println("Monday"); break; case 'b': System.out.println("Tuesday"); break; case 'c': System.out.println("Wednesday"); break; case 'd': System.out.println("Thursday"); break; case 'e': System.out.println("Friday"); break; case 'f': System.out.println("Saturday"); break; case 'g': System.out.println("Sunday"); break; default: System.out.println("No matching results, please check the input"); } System.out.println("Quit switch,But the program continues"); //output //Please enter a character a~ g //c //Wednesday //The switch exited, but the program continued to execute
-
(6) After class exercise ②: write a program, convert case, convert only a,b,c,d,e and other output
Scanner scanner = new Scanner(System.in); System.out.println("Please enter a lowercase character"); char c = scanner.next().charAt(0); //In java, as long as there is a value, the return is an expression switch(c){ case 'a': System.out.println("A"); break; case 'b': System.out.println("B"); break; case 'c': System.out.println("C"); break; case 'd': System.out.println("D"); break; case 'e': System.out.println("E"); break; default: System.out.println("other"); } //output //Please enter a lowercase character //a //A
-
(7) After class exercise ③: write a program and input a score in the hundred mark system. If it is greater than 60, the output is qualified, and if it is less than 60, the output is unqualified
Design idea: to change, int score Get the receipt and int x = score / 60;A qualified person x = 1;A failed person x = 0; case Clause use x To complete Scanner scanner = new Scanner(System.in); System.out.println("Please enter grade"); int c = scanner.nextInt(); int x = c / 60; switch(x){ case 1: System.out.println("qualified"); break; case 0: System.out.println("unqualified"); break; default: System.out.println("Incorrect input"); } //output //Please enter grade //30 //unqualified
-
(8) After class exercise ④: write a program to determine the season according to the month entered by the user (using penetration)
Scanner scanner = new Scanner(System.in); System.out.println("Please enter the month"); int c = scanner.nextInt(); switch(c){ case 3: case 4: case 5: System.out.println("spring"); break; case 6: case 7: case 8: System.out.println("summer"); break; case 9: case 10: case 11: System.out.println("autumn"); break; case 12: case 1: case 2: System.out.println("winter"); break; } //output //Please enter the month //6 //summer
4, Cycle control
1. for loop control
-
(1) Basic introduction: listen to its name, know its meaning, and let your code execute circularly
-
(2) Basic syntax:
for(Loop variable initialization ; Cycle condition ; Cyclic variable iteration){ Loop operation (statement) ;//If there is only one statement in this section, {} can be omitted, but it is not recommended }
Description: four elements: initialization of cyclic variables; Cycle conditions; Cyclic variable iteration; Loop operation (statement)
-
(3) Notes and details
0) execution sequence: initialization of cyclic variables; Judgment of cycle conditions; Enter the loop body and execute the loop operation (statement); Cyclic variable iteration
1) . return an expression of a blobean when looping conditions
2) Initialization and variable iteration in, for(; loop judgment condition;) can be written in other places, but on both sides; Cannot be omitted
3) The initialization of loop variables can have multiple initialization statements, but the types are required to be the same and separated by
4) Using memory analysis method, the following output is
int count =3; for(int i= 0,j = 0;i < count;i++,j += 2){ System.out.println("i = " + i + " j = " + j);//After the execution, the loop variable will be modified according to the loop variable iteration } //output //i = 0 j = 0 //i = 1 j = 2 //i = 2 j = 4
-
(4) Classroom practice
1) . output multiples of all 9 from 0 to 100, and count the number and sumint count = 0; int sum = 0; for(int i = 1 ; i < 100 ; i ++){ if(i % 9 == 0){ System.out.println(i); count ++; sum += i; } } System.out.println(count); System.out.println(sum); //Output 9 18 27 36 45 54 63 72 81 90 99 //11 //594 Programming ideas, you can actually, termination, multiples are represented by variables int start = 1; int end = 100; int t = 9; // multiple int count = 0; int sum = 0; for(int i = start ; i < end ; i ++){ if(i % t == 0){ System.out.println(i); count ++; sum += i; } } System.out.println(count); System.out.println(sum);
2) Output such results
//output //0+10 = 10 //1+9 = 10 //2+8 = 10 //3+7 = 10 //4+6 = 10 //5+5 = 10 //6+4 = 10 //7+3 = 10 //8+2 = 10 //9+1 = 10 //10+0 = 10
First turn complexity into simplicity, first output a column, then output a column, find out the law and merge these columns for(int i = 5,j = 0; i >= 0 ; i--,j++){ System.out.println(i + "+" + j + " = " +(i + j)); } //output 5+0 = 5 4+1 = 5 3+2 = 5 2+3 = 5 1+4 = 5 0+5 = 5 //Die before live int n=10; for(int i = 0 ; i <= n ; i++){ System.out.println(i + "+" + (n - i) + " = " + n)); }
2. whlie cycle control
-
(1) Basic syntax:
whlie(Cycle condition){ //If the cycle condition is true, enter the inside of the cycle Loop body (statement); Cyclic variable iteration; //After execution, judge the cycle condition again } while There are also four elements, just the place and for dissimilarity while After exiting, the program will continue to execute and will not terminate
-
(2) Notes and details
1) The loop condition is to return a boolean expression
2) The while loop is to judge before executing the statement
-
(3) Classroom exercises:
1) Print all numbers between 1 and 100 that can be divided by 3
int i =1; while(i < 100){ if(i % 3 == 0){ System.out.print(i + " "); } i++; } //output 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99
2) Print all even numbers between 40 and 200
//Programming idea: similarly, loop conditions can be replaced by variables int i =40; while(i < 200){ if(i % 2 == 0){ System.out.print(i + " "); } i++; }
3. do while loop control
-
(1) Basic syntax:
d0{ Loop body (statement); Cyclic variable iteration; //After execution, judge the cycle condition again }while( Cycle condition ) ;
be careful:
1) , do while are keywords2) And do while also have four elements, but they are placed in different places
3) Execute the code block first, that is, the code block must be executed at least once
4) Finally, there should be one;
5) . while is to judge first and then execute; do while is to execute first and then judge
-
(2) Notes and details
1) The loop condition is to return a boolean expression
2) do while is to execute first and then judge. The code block in the loop is executed at least once -
(3) Classroom exercises:
Print all numbers between 1 and 100; Count their sum;
int i = 1; int sum = 0; int j = 1; int count = 0; char answer; do{ System.out.println(i); sum += i; i++; }while( i <= 100); System.out.print("1 ~ 100 The sum of is" + sum);
Count the number of 1 ~ 200 that can be divided by five but cannot be divided by 0 and 3;
//Train of thought analysis statistics 1 ~ 200 can be divided by five but can not be divided by three //Output 1 - 200 first //Then judge% 5 = = 0 & &% 3= 0 //Count the number of qualified //Number of outputs do{ if(j % 5 == 0 && j % 3 != 0){ count++; } j++; }while( j <= 200); System.out.println("1 ~ 200 What are the numbers that can be divided by five but not by 0 and 3" + count + " individual");
If Zhang San doesn't pay back, he will call until he pays back
do{ System.out.println("I ask you, do you pay back the money?"); Scanner scanner = new Scanner(System.in); System.out.println("Please enter your answer( y/n)"); answer = scanner.next().charAt(0); System.out.println("His answer is" + answer); j++; }while( answer == 'n'); System.out.println("You finally paid back the money");
4. Multiple cycle control
-
(1) I. Basic Introduction
1) A nested loop is formed when a loop is placed in another loop. for/ while/ do while can be used as inner loop and outer loop [it is recommended to generally use two layers, not more than three layers]2) In essence, nested loops regard the inner loop as the loop body of the outer loop. When the loop condition of the inner loop is false, it will completely jump out of the inner loop, end the current loop of the outer loop and start the next loop
3) . if the number of outer layer cycles is m times and the number of inner layer cycles is n times, the inner layer cycle body actually needs to execute m * n times
4) . case analysis
for(int i = 0;i < 2;i++){ for(int j = 0; j < 3;j++){ System.out.println("i = " + i + "j = " + j); } } //output //i = 0 j = 0 //i = 0 j = 1 //i = 0 j = 2 //i = 1 j = 0 //i = 1 j = 1 //i = 1 j = 2
-
(2) Class practice
1) Count the results of the three classes. There are 5 students in each class. Calculate the average score of each class and the average score of all classes [students' scores are input from the keyboard], and calculate the number of passing students in the three classes. There are 5 students in each class//simplify what is complicated //1.1. Count the scores of 5 students in a class; A single-layer averaging cycle //1.2. Get the average score of a class, accumulate all scores, and then score equally //2.1. Count the average score of three classes. One class cycle is nested outside the average score cycle //3.1. Count the number of people who have passed, define a count, and judge whether the received grade is passed in the class average score cycle. if statement count++ Scanner scanner = new Scanner(System.in); double score = 0; double sum = 0; //Count the total score of the class for average use double ave = 0; //Calculate average score double total_score = 0;//Average score of three classes int count = 0; //Calculate the total number of people who have passed for(int i = 1; i <= 3; i++){ //i indicates that the class can be optimized again to use variables for(int j = 1;j <= 5;j++){//j means student System.out.println("Please enter page" + i + "The second class " + j +"A student's grade"); score = scanner.nextDouble();//Get keyboard input System.out.println("The results are:" + score ); if(score >= 60){//Pass judgment count++; } sum += score; //Get class scores total_score += score;//Get total score } ave = score / 5; System.out.println("\n The first" + i + "The average score of each class is: " + ave ); } total_score /= 15; System.out.println("\n The average score of all classes is: " + total_score ); System.out.println("\n The number of passes in all classes is: " + count );
2) Print and output 99 multiplication table
//simplify what is complicated //0 and 1 output 9 lines first, and the single-layer for loop //0, 2 complete the following goals in each line //1.1. Output 1 in the first row, 2 in the second row, and so on, that is, each row has one more column than the previous row, //1.2. First output 1 * 1 = 1 to the number of rows in each row. 1 * number of rows = number of rows. The output of each row should not be wrapped. Only after one row is output will it wrap //2.1. Count the average score of three classes. One class cycle is nested outside the average score cycle //3.1. Count the number of people who have passed, define a count, and judge whether the received grade is passed in the class average score cycle. if statement count++ //The number of rows can be replaced by variables to complete more multiplication tables for(int i = 1; i <= 9; i++ ){ // i is the number of rows for(int j = 1; j <= i; j++){// j is the number of columns in each row. The number of columns should be equal to the number of rows at most System.out.print( j + " * " + i + " = " + (i * j) + '\t' );//Output multiplication formula } System.out.println();//Wrap } //Output results //1 * 1 = 1 //1 * 2 = 2 2 * 2 = 4 //1 * 3 = 3 2 * 3 = 6 3 * 3 = 9 //1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16 //1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 //1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36 //1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49 //1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64 //1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
3) , printout, hollow pyramid
* * * * * * * * * ***********
-
//1.1. Output a right triangle first*
int totalLever =6;//Number of layers for(int i = 1; i <= totalLever; i++ ){ // i is the number of rows for(int j = 1; j <= i ; j++){// j is the number of columns in each row. The number of columns should be equal to the number of rows at most System.out.print("*");//Output* } System.out.println();//Wrap } * ** *** **** ***** ******
-
//1.2. Then complete the right triangle above into an isosceles triangle
* *** ***** ******* ********* *********** *************
-
//1.3. The first line moves (number of last line - number of first line) / 2,
The second row moves (number of the last row - number of the second row) / 2,
The next movement rule is similar, and the solid pyramid is output first
-
//1.4 after moving, the number of * printed on each line is
Number of rows * number 1 1 2 3 3 5 4 7 Get the rule: *number = Number of rows X 2 - 1
int totalLever =6;//Number of layers for(int i = 1; i <= totalLever; i++ ){ // i is the number of rows for(int k = 0; k < totalLever - i; k++){ System.out.print(" ");//Output space, move position } for(int j = 1; j <= i* 2 - 1 ; j++){// j is the number of columns in each row. The number of columns should be equal to the number of rows at most System.out.print("*");//Output* } System.out.println();//Wrap }
-
//2. Make hollow
* * * * * * * * * * *
// Let the first and last positions of each line print *, // The first position is the space, and the end position is: j == 1 // The last position is the position of the last * of the original solid pyramid: 2 * current number of rows - 1, // Insert the if conditional judgment statement in the loop of printing *, which is |, otherwise the space will be output int totalLever =6;//Number of layers for(int i = 1; i <= totalLever; i++ ){ // i is the number of rows for(int k = 0; k < totalLever - i; k++){ System.out.print(" ");//Output space, move position } for(int j = 1; j <= i * 2 - 1 ; j++){// j is the number of columns in each row. The number of columns should be equal to the number of rows at most if(j == 1 || j == i * 2 -1 ){ System.out.print("*");//Output* }else{ System.out.print(" ");//Output* } } System.out.println();//Wrap }
-
//3. Make up the last line and add a judgment to judge whether this line is the last line. If so, directly output all *. This can be placed on the output space above, so there is no need to write an if
* * * * * * * * * ***********
int totalLever =6;//Number of layers for(int i = 1; i <= totalLever; i++ ){ // i is the number of rows for(int k = 0; k < totalLever - i; k++){ System.out.print(" ");//Output space, move position } for(int j = 1; j <= i * 2 - 1 ; j++){// j is the number of columns in each row. The number of columns should be equal to the number of rows at most if(j == 1 || j == i * 2 -1 || i == totalLever){ System.out.print("*");//Output* }else{ System.out.print(" ");//Output* } } System.out.println();//Wrap }
-
//4. The ultimate version: die first and live later, in which the number of rows can be replaced by variables to complete more hollow pyramids
Scanner scanner = new Scanner(System.in); System.out.println("Please enter the number of layers of the hollow pyramid you want to print:");//Output* int totalLever =scanner.nextInt();//Number of layers for(int i = 1; i <= totalLever; i++ ){ // i is the number of rows for(int k = 0; k < totalLever - i; k++){ System.out.print(" ");//Output space, move position } for(int j = 1; j <= i * 2 - 1 ; j++){// j is the number of columns in each row. The number of columns should be equal to the number of rows at most if(j == 1 || j == i * 2 -1 || i == totalLever){ System.out.print("*");//Output* }else{ System.out.print(" ");//Output* } } System.out.println();//Wrap } //output //Please enter the number of layers of the hollow pyramid you want to print: //8 * * * * * * * * * * * * * ***************
-
5, Jump control statement break -- for loop control
-
1. Basic introduction
Listen to its name and know its meaning, so that your code can be executed in a loop, and all loops can be used inside
-
2. Basic grammar
{ ... break; .... }
-
3. Quick start
for(int i = 1; i <= 10; i++ ){ if (i == 3){ break; } System.out.println("i = " + i); } //output //i = 1 //i = 2
-
4. Notes and details
(1) The break statement appears in the statement block in the multi-layer nesting, and the label can indicate which layer of statement block to terminate
(2) Basic use of labels
1) , grammarlabel1:{... label2: {... label3: {... ... break label2; ... } } }
2) Note:
① And berak statements can specify which layer to exit② label1. The label is specified by the programmer. The label can be written in any format, which can meet the identifier naming rules
③ . break will be launched wherever the label is specified
④ In the actual development, try not to use labels
⑤ . if break is not specified, the nearest loop body will be pushed by default
#) practical application
abc1: for(int i = 1; i <=4; i++ ){ abc2:for(int j = 1; j <= 2; j++ ){ if(i == 2){ break;//Equivalent to exiting abc2 / / output I = 1 I = 2 I = 3 I = 4 //reak abc1; // Output i = 1 } } System.out.println("i = " + i); }
-
4. Classroom practice
(1) Sum the data within 1 - 100 to find the current number when the sum is greater than 20 for the first time//If you want to output I outside the for loop, you need to define a variable n, or define I outside the loop (int i = 0;); int sum = 0; int n = 0; for(int i = 1; i <=100; i++ ){ n = i; sum += i; if(sum > 20){ System.out.println("The cumulative sum is greater than 20"); System.out.println("i = " + i); break; } } System.out.println("i = " + n);//Output i = 6 //output //The cumulative sum is greater than 20 //i = 6
(2) There are three opportunities to realize login verification. If the user name is "Chen Ran" and the password is "666", it will prompt that the login is successful. Otherwise, it will prompt that there are still several opportunities
Idea: use for Loop nesting. If the password is entered correctly, use break sign out for loop Design a variable of login opportunity. Every time it fails, it will -- ,Then judge == 0 ?, If != ,There are still several opportunities, if ==0,The password you entered is wrong and the page is refreshed Scanner scanner = new Scanner(System.in); String name = ""; String password = ""; int chance = 3; for(int i = 1; i <=3; i++ ){ System.out.println("Please enter your user name:"); name = scanner.next(); System.out.println("Please enter your user name:"); password = scanner.next(); if("Chen Ran".equals(name) && "666".equals(password)){ System.out.println("Login successful"); break; }else{ chance--; System.out.println("You have" + chance + "Second chance"); } } //output //Please enter your user name: //Chen Xin //Please enter your user name: //666 //You have two more chances //Please enter your user name: //Chen Ran //Please enter your user name: //666 //Login successful
6, Jump control statement continue
-
(1) I. Basic Introduction
1. The continue statement is used to end this loop and continue to execute the next loop. When continue is executed, the iteration of loop variables is automatically completed, and then the next loop condition judgment is started
2. When the continue statement appears in a multi-layer nested loop statement, you can use the label to skip the loop of that layer. If you don't write the label, you will jump out of the nearest loop by default. The use method is the same as the label in break. It is not expanded here
-
(2) , grammar
{ ... continue; ... }
-
(3) Class practice
int i = 1; while(i <= 4){ i++; if(i ==2){ continue; } System.out.println("i = " + i); } //output //i = 3 //i = 4 //i = 5
7, Jump control statement return
-
(1) I. Basic Introduction
return when used in a method, it means to jump out of the method. If it is written in the main() method, it will exit the program
-
(2) Class practice
for(int i = 1; i <=3; i++ ){ if(i == 2){ System.out.println("ii"); //return; // Output helloworld ii //continue; // Output Hello World II Hello World break; //Output Hello World II hello } System.out.println("helloworld"); } System.out.println("Hello");
8, After class practice
- (1) Programming to achieve the following functions
Someone has 100000 yuan and has to pay a fee for each intersection. The rules are as follows
5% each time when cash > 50000
When cash < = 50000, pay 1000 each time
Q: how many intersections can you pass (while break)//Train of thought analysis //The condition of while is that your money is greater than 0, so you define a variable to save money and a variable to store the number of intersections you pass //An IF statement is written inside the while to deduct money. The amount range of money under the if condition is > 50000, and the range of else if is < = 50000 //Then deduct money from the execution statement block of if //There is also an if in the above else if to judge whether the money is enough to pass the next intersection, that is, money > = 1000?, If not, break int count = 0; double money = 100000; while(true){ if(money > 50000){ money = money * 0.95; count++; }else if( money >= 1000){ money -= 1000; count++; }else{ break; } } System.out.println("You've passed " + count + " Intersection");//62
- (2) Judge whether a number is narcissus number narcissus number: the sum of cubes at each position of a three digit number is equal to itself, for example, 153 = 111 + 333 + 555
//The idea is to find the specific values of one digit, ten digit and hundred digit, and then if (judge whether the formula is true) Scanner scanner = new Scanner(System.in); System.out.println("Please enter a number:"); int n = scanner.nextInt(); int ge = n % 10; int shi = (n%100)/10; int bai = n/100; if(ge*ge*ge + shi*shi*shi + bai*bai*bai == n ){ System.out.println(n + " It's a daffodil number"); }else{ System.out.println(n + " Not a daffodil number"); } //Find the number of daffodils of 100 - 1000 for(int i = 100; i <1000; i++ ){ int ge = i % 10; int shi = (i%100)/10; int bai = i/100; if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i ){ System.out.println(i + " It's a daffodil number");//371 153 370 407 } }
- (3) Output all the numbers divided by 5 between 1 and 100, and 5 are 1 line
//Idea: //Determine whether to divide 5 //Define a variable to store the number of outputs of each line. After reaching 5, start the line feed operation int count = 0; for(int i = 1; i <=100; i++ ){ if(i % 5 == 0){ System.out.print((i) +" \t"); count ++; if(count == 5){ System.out.println(); count = 0; } } } //5 10 15 20 25 //30 35 40 45 50 //55 60 65 70 75 //80 85 90 95 100
- (4) , output lowercase a - z and uppercase Z - A
//Idea: //The essence of a character is a code. We can operate on this code. The next step is loop + /- char small_a = 97; char big_Z = 90;//Uppercase characters = lowercase characters - 22 for(int i = 0; i <25; i++ ){ System.out.print(small_a + " "); small_a ++; } System.out.println(); for(int i = 0; i <25; i++ ){ System.out.print(big_Z + " "); big_Z --; } System.out.println();
- (5) . find the value of 1 - 1 / 2 + 1 / 3 - 1 / 4... 1 / 100
//thinking //The denominator increases gradually and is completed with for //The numerator is 1 / - 1 to switch back and forth. You only need to judge the number of digits (even digit is negative and odd digit is positive) double sum = 0; for(int i = 1; i <= 100; i++ ){ if(i % 2 == 0){ sum -= 1.0/i ;//Hide the trap and write the 1 of the molecule as 1.0 }else{ sum += 1.0/i; } } System.out.println(sum);//Output 0.688172179310195
- (6) . find the result of 1 + (1 + 2) + (1 + 2 + 3) +... + (1 + 2 + 3 +... + 100)
//How many times + is the outer layer of the double-layer cycle, and provide the end value of addition for the inner layer int sum = 0; for(int i = 1; i <= 100; i++ ){ for(int j = 1; j <= i; j++ ){ sum += j ; } } System.out.println(sum);//171700