1. Program flow control overview
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
- Branching structure
- Cyclic structure
1. Sequential structure
The program is executed line by line from top to bottom without any judgment and jump.
2. Branching structure
- Selectively execute a piece of code according to conditions.
- There are two branch statements: if... else and switch case.
3. 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.
2. Sequential structure
Legal forward references are used when defining member variables in Java. For example:
3. Branching structure
3.1 branch statement 1: if else structure
1. If else instructions:
- Conditional expression must be Boolean expression (relational expression or logical expression) and boolean variable;
- When there is only one execution statement in the statement block, a pair of {} can be omitted, but it is recommended to keep it;
- If else statement structure, which can be nested as needed;
- When the if else structure is "one out of many", the last else is optional and can be omitted as needed;
- When multiple conditions are mutually exclusive, the order between condition judgment statements and execution statements does not matter. When multiple conditions are inclusive, the order is "small up and large down / child up and parent down".
2. Practice
package day03; /* If else in branch structure Three structures First: if(Conditional expression){ Execute expression } Second: choose one from two if(Conditional expression){ Execute expression 1 }else{ Execute expression 2 } Third: choose one more if(Conditional expression){ Execute expression 1 }else if{ Execute expression 2 }else if(Conditional expression){ Execute expression 3 } ... else{ Execute expression n } */ public class IfTest { public static void main(String[] args) { int heartBeats = 79; if(heartBeats<60||heartBeats>100) { System.out.println("Further inspection is required"); } System.out.println("End of inspection"); int age = 23; if(age>18) { System.out.println("adult"); } else { System.out.println("juveniles"); } if(age<0) { System.out.println("data is invalid"); } else if(age<18) { System.out.println("juveniles"); } else if (age<35) { System.out.println("office worker"); } else if(age<60) { System.out.println("controller"); } else { System.out.println("Retiree"); } } }
3. Input statement
package day04; /* How to get different types of variables from the keyboard requires the Scanner class Specific steps: 1.Guide Package: import java.util.Scanner; 2.Scanner Instantiation of; 3.Call the relevant methods of the Scanner class to obtain the specified variables. 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 will be reported: InputMisMatchException causes the program to terminate */ import java.util.Scanner; public class ScannerTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter your name:"); String name = scanner.next(); System.out.println("Please enter your age:"); int num = scanner.nextInt(); System.out.println("Please enter your weight:"); double weight = scanner.nextDouble(); System.out.println("Are you married?"); Boolean isMarried = scanner.nextBoolean(); //For char type acquisition, Scanner does not provide it, but can only obtain strings System.out.println("Please enter gender:"); String gender = scanner.next(); char genderChar = gender.charAt(0);//Gets the character at position with index 0 System.out.println(name); System.out.println(num); System.out.println(weight); System.out.println(isMarried); System.out.println(genderChar); } }
package day04; /* Yue Xiaopeng took the Java exam. He and his father Yue buqun made a commitment: If the score is 100, a BMW will be rewarded; When the score is (80, 99], an iphone xs max will be awarded; When the score is [60,80], reward an iPad; Other times, there is no reward. Please input Yue Xiaopeng's final grade from the keyboard and judge it explain: 1.else Structure is optional. 2.For conditional expressions: ① If the relationship between multiple conditional expressions is "mutually exclusive" (or has no intersection), it doesn't matter which judgment and execution statement is declared above or below; ② If there is an intersection relationship between multiple conditional expressions, you need to consider the actual situation according to the actual situation, and consider which structure should be declared on it. ③ If there is an inclusive relationship between multiple conditional expressions, it is usually necessary to declare the small range on the large range. Otherwise, the small range will have no chance to run. */ import java.util.Scanner; public class IfTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter your final grade:(0-100)"); int score = scanner.nextInt(); //Choose one more if (score == 100) { System.out.println("Reward one BMW"); } else if (score>80 &&score<=99) { System.out.println("Reward one iphone xs max"); } else if (score>=60 &&score<=80) { System.out.println("Reward one iPad"); } else { System.out.println("No reward"); } } }
package day04; /* Programming: input three integers from the keyboard and store them into variables num1, num2 and num3 respectively, They are sorted (using if else if else) and output from small to large. explain: 1. if-else Structures can be nested 2. if-else When there is only one line of execution statement in the structure, {} can be removed, but it is not recommended */ import java.util.Scanner; public class ifTest2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter the first integer"); int num1 = in.nextInt(); System.out.println("Please enter the second integer"); int num2 = in.nextInt(); System.out.println("Please enter the third integer"); int num3 = in.nextInt(); if(num1>=num2) { if (num3>=num1) { System.out.println(num2+"\t"+num1+"\t"+num3); } else if (num3<=num2) { System.out.println(num3+"\t"+num2+"\t"+num1); } else { System.out.println(num2+"\t"+num3+"\t"+num1); } } else { if (num3<=num1) { System.out.println(num3+"\t"+num1+"\t"+num2); } else if (num3>=num2) { System.out.println(num1+"\t"+num2+"\t"+num3); } else { System.out.println(num1+"\t"+num3+"\t"+num2); } } //Get random number int num = (int)(Math.random()*90+10);//[10-99] //Formula: [a,b]: (int)(Math.random()*(b-a+1)+a) } }
/* My dog is 5 years old. How old is a 5-year-old dog equivalent to a human? In fact, each year of the first two years of a dog is equivalent to 10.5 years of human age, and then every additional year will increase by four years. So how old is a 5-year-old dog equivalent to a human? It should be: 10.5 + 10.5 + 4 + 4 = 33 years old. If the user enters a negative number, a prompt is displayed. */ import java.util.Scanner; class DogYear{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please enter the dog's age:"); double Dyear = scan.nextDouble(); if(Dyear <= 2 && Dyear > 0){ System.out.println("The age of a dog is equal to that of a man:" + Dyear * 10.5); }else if(Dyear <= 0){ System.out.println("Your input is incorrect."); }else{ double number = 2 * 10.5 + (Dyear - 2) * 4; System.out.println("The age of a dog is equal to that of a man:" + number); } } }
/* Suppose you want to develop a lottery game, and the program randomly generates a two digit lottery, Prompt the user to enter a two digit number, and then determine whether the user can win according to the following rules. 1)If the number entered by the user matches the actual order of the lottery, the bonus is $10000. 2)If all the numbers entered by the user match all the numbers of the lottery, but the order is inconsistent, the bonus is $3000. 3)If a number entered by the user matches only one number of the lottery ticket in order, a bonus of $1000 will be awarded. 4)If a number entered by the user meets only one number matching the lottery ticket in non sequential case, the bonus is $500. 5)If the number entered by the user does not match any number, the lottery will be voided. Tip: use (int) (math. Random() * 90 + 10) to generate random numbers. Math.random() : [0,1) * 90 [0,90) + 10 [10,100)[10,99] */ import java.util.Scanner; class CaiTest{ public static void main(String[] args){ //1. Randomly generate a two digit number //System.out.println(Math.random()); / / generate [0,1] int number = (int)(Math.random()*90 + 10);//Get [10,99], i.e. [10100) //System.out.println(number); int numberShi = number/10; int numberGe = number%10; //2. The user enters a two digit number Scanner input = new Scanner(System.in); System.out.print("Please enter a two digit number:"); int guess = input.nextInt(); int guessShi = guess/10; int guessGe = guess%10; if(number == guess){ System.out.println("Bonus $10000"); }else if(numberShi == guessGe && numberGe == guessShi){ System.out.println("Bonus $3000"); }else if(numberShi==guessShi || numberGe == guessGe){ System.out.println("Bonus $1000"); }else if(numberShi==guessGe || numberGe == guessShi){ System.out.println("Bonus $500"); }else{ System.out.println("Didn't win the prize"); } System.out.println("The winning number is:" + number); } }
package day04; /* As we all know, men should marry, women should marry. If the woman's parents want to marry their daughter, of course, they must put forward certain conditions: height: more than 180cm; Fu: more than 10 million; Shuai: Yes. If these three conditions are met at the same time, then: "I must marry him!!!" If the three conditions are true, then: "marry, less than the top, more than the bottom." If the three conditions are not met, then: "don't marry!" */ import java.util.Scanner; public class IfExer { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter your height:( cm)"); int height = in.nextInt(); System.out.println("Please enter your treasury shares: (ten million)"); double wealth = in.nextDouble(); System.out.println("Please enter whether you are handsome:( true/false)"); Boolean isHandsome = in.nextBoolean(); if (height>=180&& wealth>=1&& isHandsome) { System.out.println("I must marry him!!!"); } else if (height>=180|| wealth>=1|| isHandsome) { System.out.println("Marry, not enough than the top, more than the bottom"); } else { System.out.println("Not married"); } } }
3.2 branch statement 2: switch case structure
Note: the expression in the switch structure can only be one of the following six data types: byte, short, char, int, enumeration type (JDK5.0) and String type (JDK7.0)
Cannot be: long, float, double, boolean.
package day04; /* Branch structure 2: switch case 1.format switch((expression){ case Constant 1: Execute statement 1; //break; case Constant 2: Execute statement 2; //break; ... default: Execute statement n: //break; } 2.explain: ① Match the constants in each case according to the values in the switch expression. Once the matching is successful, enter the corresponding case structure and execute relevant statements. After the execution statement is called, other case statements continue to be executed downward until the break keyword or the end is encountered. ② break, You can use the switch case structure to indicate that once this keyword is executed, it will jump out of the switch case structure. ③ switch The expression in the structure can only be one of the following six data types: byte, short, char, int, enumeration type (JDK5.0), String type (JDK7.0) ④ case Subsequent can declare constants. Cannot declare ranges. ⑤ break Keywords are optional. ⑥ default: It is equivalent to else in the if else structure. default The structure is optional and the location is flexible. */ public class SwitchCaseTest { public static void main(String[] args) { int num = 2; switch (num) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; default: System.out.println("other"); } 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("Season input error"); break; } } }
/* Use switch to convert lowercase char to uppercase. Only convert a, b, c, d, e. other output "other". Prompt: String word = scan. Next(); char c = word. Charat (0); switch (c) {} */ import java.util.Scanner; class SwitchCaseTest1{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); String word = scan.next(); char c = word.charAt(0); 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"); } } }
package day04; /* Students with scores greater than 60 will be output as "qualified". Those with scores lower than 60 will be output as "unqualified". Note: if there are multiple identical statements in the switch case statement, they can be merged. */ public class SwitchCaseTest1 { public static void main(String[] args) { int score = 59; switch (score/60) { case 0: System.out.println("fail,"); break; default: System.out.println("pass"); } } }
/* Print the season of the month according to the specified month. 3,4,5 Spring 6, 7, 8, summer 9, 10, 11, autumn 12, 1, 2, winter */ class MonthTest{ public static void main(String[] args){ int month = 6; switch(month){ case 12: case 1: case 2: System.out.println("winter"); break; 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; } } }
package day04; /* Programming: input "month" and "day" of 2021 from the keyboard, The date required to be input through program output is the day of 2021. 2 15 : 31 + 15 5 7: 31 + 28 +31 +30 + 7 ... Note: break is optional in switch case. */ import java.util.Scanner; public class SwitchCaseTest2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter month:"); int month = in.nextInt(); System.out.println("Please enter the day:"); int day = in.nextInt(); //Define a variable to hold the total number of days int sumDays = 0; switch (month) { case 12: sumDays +=30; case 11: sumDays +=31; case 10: sumDays +=30; case 9: sumDays +=31; case 8: sumDays +=31; case 7: sumDays +=30; case 6: sumDays +=31; case 5: sumDays +=30; case 4: sumDays +=31; case 3: sumDays +=28; case 2: sumDays +=31; case 1: sumDays +=day; } System.out.println(sumDays); } }
package day04; /* Enter the year, month and day respectively from the keyboard to judge the day of the year. Note: the criteria for judging whether a year is a leap year: 1)Can be divided by 4, but not by 100 or 2)It can be divided by 400 (year % 4 == 0 && year % 100 != 0) || year %400 == 0) explain: 1 Any structure that can use switch case can be converted to if else. On the contrary, it does not hold. 2.When we write the branch structure, we find that we can use switch case [(at the same time, there are not many values of expressions in switch), You can also use if else. We prefer to use switch case. Reason: the execution efficiency of switch case is slightly higher. */ import java.util.Scanner; public class SwitchCaseExer { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter the year:"); int year = in.nextInt(); System.out.println("Please enter month:"); int month = in.nextInt(); System.out.println("Please enter the day:"); int day = in.nextInt(); //Define a variable to hold the total number of days int sumDays = 0; switch (month) { case 12: sumDays +=30; case 11: sumDays +=31; case 10: sumDays +=30; case 9: sumDays +=31; case 8: sumDays +=31; case 7: sumDays +=30; case 6: sumDays +=31; case 5: sumDays +=30; case 4: sumDays +=31; case 3: //sumDays +=28; if((year%4==0&&year%100!=0)||year%400==0) { sumDays += 29; } else { sumDays +=28; } case 2: sumDays +=31; case 1: sumDays +=day; } System.out.println(sumDays); } }
/* Write a program to find the corresponding Chinese Zodiac for a given year. The Chinese zodiac is based on a 12-year cycle and is represented by an animal every year: rat,ox,tiger,rabbit,dragon,snake,horse,sheep,monkey,rooster,dog,pig. Tip: 2019: Pig% 12 = = 3 */ import java.util.Scanner; class ZodiacSignTest{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Please enter the year:"); int year = scan.nextInt(); switch (year % 12){ case 1: System.out.println("rooster"); break; case 2: System.out.println("dog"); break; case 3: System.out.println("pig"); break; case 4: System.out.println("rat"); break; case 5: System.out.println("ox"); break; case 6: System.out.println("tiger"); break; case 7: System.out.println("rabbit"); break; case 8: System.out.println("dragon"); break; case 9: System.out.println("snake"); break; case 10: System.out.println("horse"); break; case 11: System.out.println("sheep"); break; case 12: System.out.println("monkey"); break; } } }
4. Cyclic structure
1. Cyclic structure
When certain conditions are met, the function of specific code is executed repeatedly
2. Circular statement classification
- for loop
- while loop
- Do while loop
4.1 for loop
Syntax format for(①Initialization part;②Cycle condition section;④Iterative part){ ③Circulating body part; } Execution process:①-②-③-④-②-③-④-②-③-④-.....-② explain: ②The cycle condition part is boolean Type expression when the value is false When, exit the loop ①The initialization part can declare multiple variables, but they must be of the same type, separated by commas ④There can be multiple variable updates, separated by commas
package day04; /* For Use of circular structure 1, Four elements of circular structure ① Initialization condition ② Cycle condition ③ Circulatory body ④ Iterative condition 2, Structure of for loop for(①;②;④){ ③ } */ public class ForTest { public static void main(String[] args) { for (int i=0; i<50; i++) { System.out.println("Hello,world"); } int num =1; for (System.out.println('a');num<=3;System.out.println('c'),num++) { System.out.println('b'); } //Traverse even numbers within 100 and output even numbers and //i is valid within the loop, but invalid outside the for loop int sum = 0;//Record even and int count = 0;//Record even number for (int i = 1; i<100; i++) { if(i%2==0) { System.out.println(i); sum += i; count++; } } System.out.println(sum); System.out.println(count); } }
package day04; /* Write a program to cycle from 1 to 150 and print a value on each line, In addition, "foo" is printed on each multiple line of 3, Print "biz" on each multiple line of 5, Print out "baz" on each multiple line of 7. */ public class ForTest1 { public static void main(String[] args) { for (int i=1; i<=150; i++) { System.out.print(i+"\t"); if(i%3==0) { System.out.print("foo\t"); } if (i%5==0) { System.out.print("biz\t"); } if (i%7==0) { System.out.print("baz\t"); } //Line feed System.out.println(); } } }
package day05; /* Enter two positive integers m and n to find their maximum common divisor and minimum common multiple. For example, the maximum common divisor of 12 and 20 is 4 and the minimum common multiple is 60. Note: the use of the break keyword will jump out of the loop once the break is executed in the loop */ import java.util.Scanner; public class ForTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter the first positive integer"); int m = in.nextInt(); System.out.println("Please enter the second positive integer"); int n = in.nextInt(); //Get the maximum common divisor //1. Get the smaller of two numbers int min = m<=n?m:n; //2. Traversal for (int i = min; i>=1; i--) { if (m%i==0&& n%i==0) { System.out.println("The maximum common divisor is:"+i); break;//Once a break is executed in a loop, it jumps out of the loop } } //Get least common multiple //1. Get the larger of the two numbers int max = m>=n?m:n; //2. Traversal for (int i=max; i<m*n; i++) { if (i%m==0&& i%n==0) { System.out.println("The minimum common multiple is:"+i); break; } } } }
/* Output all the daffodils. The so-called daffodils number refers to a 3-digit number, and the sum of the number cubes on each digit is equal to itself. For example: 153 = 1 * 1 * 1 + 3 * 3 * 3 + 5 * 5 * 5 */ class ForTest2{ public static void main(String[] args){ for(int i = 100;i <= 999;i++){ int a = i / 100; //Get hundreds int b = i % 100 /10; //Get ten digits int c = i % 10; //Get bits if(a*a*a + b*b*b + c*c*c == i){ System.out.println("This value is the number of daffodils that meet the conditions:" + i); } } } }
4.2 while loop
①Initialization part while(②Cycle condition section){ ③Circulating body part; ④Iterative part; }
Execution process: ① - ② - ③ - ④ - ② - ③ - ④ - ② - ③ - ④ -... - ②
explain:
- Be careful not to forget to declare the ④ iteration part. Otherwise, the loop will not end and become an dead loop.
- for loops and while loops can be converted to each other.
package day05; /* While Use of circular structure 1, Four elements of circular structure ① Initialization condition ② Cycle condition ③ Circulatory body ④ Iterative condition 2, Structure of while loop ①Initialization part while(②Cycle condition part) ③Circulating body part; ④Iterative part; } Execution process: ① - ② - ③ - ④ - ② - ③ - ④ -... - ② explain: 1.When writing a while loop, be careful not to lose the iteration condition. Once lost, it may lead to an endless loop! 2.Write programs to avoid dead cycles. 3.If you can use a while loop, you can use a for loop, and vice versa. The two can be converted to each other. Difference: the scope of the initialization condition part of the for loop and the while loop is different. Algorithm: finiteness. */ public class WhileTest { public static void main(String[] args) { //Traverse all even numbers within 100 int i = 1; while (i<=100) { if (i%2==0) { System.out.println(i); } i++; } System.out.println(i); } }
4.3 do while cycle
package day05; /* do-while Use of circular structure 1, Four elements of circular structure ① Initialization condition ② Loop condition -- > is of boolean type ③ Circulatory body ④ Iterative condition 2, Structure of do while loop ① do{ ③; ④; }while(②); Execution process: ① - ③ - ④ - ② - ① - ③ - ④ -... - ② explain: 1. do-while Loop executes the loop body at least once. 2. In development, for loop and while loop are used more */ public class DoWhileTest { public static void main(String[] args) { //Traverse even numbers within 100, and record the sum of all even numbers and the number of even numbers int i = 1; int sum = 0;//Records and int count = 0;//Number of records do { if (i%2==0) { System.out.println(i); sum += i; count ++; } i++; } while (i<=100); System.out.println(sum); System.out.println(count); int num1 = 10; while (num1>10) { System.out.println("while"); num1--; } int num2 = 10; do { System.out.println("do-while"); num2--; } while (num2>10); } }
package day05; /* Read an uncertain number of integers from the keyboard, judge the number of positive and negative numbers, and enter 0 to end the program. explain: 1.Structures that do not limit the number of times in the loop condition: while (true), for (true) 2.Several ways to end the cycle: Method 1: the loop condition part returns false; Mode 2: execute break in the loop body; */ import java.util.Scanner; public class ForWhileTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); int number; int positiveNumber = 0;//Record positive number int negativeNumber = 0;//Record negative number //while (true) { for (; true; ) { number = in.nextInt(); if (number == 0) { break; } else if (number>0) { positiveNumber++; } else { negativeNumber++; } } System.out.println("The number of positive numbers is"+positiveNumber); System.out.println("The number of negative numbers is"+negativeNumber); } }
4.4 nested loop structure
1. Nested loops (multiple loops)
- A nested loop is formed when one loop is placed in another loop. For, while, do... While can be used as an outer loop or an inner loop.
- In essence, nested loops treat the inner loop as the loop body of the outer loop. Only when the loop condition of the inner loop is false, will it completely jump out of the inner loop, end the current loop of the outer loop and start the next loop.
- Let the outer layer cycle times be m times and the inner layer cycle times be n times, then the inner layer cycle body actually needs to execute m*n times.
2. Example:
- multiplication table
- All prime numbers within 100
package day05; /* Use of nested loops 1.Nested loop: declaring one loop structure A in the loop body of another loop structure B constitutes A nested loop 2. Outer circulation: circulation structure B Inner circulation: circulation structure A 3.explain ① The inner loop 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 is executed m * n times 4.skill The outer loop controls the number of rows and the inner loop controls the number of columns */ public class ForForTest { public static void main(String[] args) { for (int i=1; i<=6; i++) { System.out.print("*\t"); } System.out.println("\n"); for (int i=1; i<=4; i++) { for (int j=1; j<=6; j++) { System.out.print("*\t"); } System.out.println(); } System.out.println(); for (int i=1; i<=5; i++) { for (int j=1; j<=i; j++) { System.out.print("*\t"); } System.out.println(); } System.out.println(); for (int i=1; i<=4; i++) { for (int j=1; j<=5-i; j++) { System.out.print("*\t"); } System.out.println(); } System.out.println(); for (int i=1; i<=10; i+=2) { for (int j=1; j<10-i; j+=2) { System.out.print("\t"); } for (int j=1; j<=i; j++) { System.out.print("*\t"); } System.out.println(); } System.out.println(); } }
package day05; /* multiplication table */ public class NineNineTable { 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(); } } }
package day05; /* 100 All prime numbers within Prime: prime, a natural number that can only be divided by 1 and itself. --->From 2 to the end of the number - 1, it cannot be divided by itself The minimum prime number is: 2 */ public class PrimeNumberTest { public static void main(String[] args) { //Gets the number of milliseconds from 1970-01-01 00:00:00 in the current time long start = System.currentTimeMillis(); boolean isFlag = true;//Can i not be divided by j int count = 0;//Record prime number for (int i=2; i<=10000; i++) { // for (int j=2; j<i; j++) { for (int j=2; j<Math.sqrt(i); j++) {//Optimization: valid for prime numbers if (i%j==0) { isFlag = false; break;//Optimization: valid for non prime numbers } } if (isFlag) { System.out.println(i); count++; } //Reset isFlag = true; } System.out.println("The number of prime numbers is"+count); long end = System.currentTimeMillis(); System.out.println("The time taken is"+(end - start)); } }
package day05; public class PrimeNumberTest2 { public static void main(String[] args) { //Gets the number of milliseconds from 1970-01-01 00:00:00 in the current time long start = System.currentTimeMillis(); boolean isFlag = true;//Can i not be divided by j int count = 0;//Record prime number label:for (int i=2; i<=10000; i++) { // for (int j=2; j<i; j++) { for (int j=2; j<Math.sqrt(i); j++) {//Optimization: valid for prime numbers if (i%j==0) { isFlag = false; //break;// Optimization: valid for non prime numbers continue label; } } // if (isFlag) { // System.out.println(i); // count++; // } //All the numbers that can perform this step are prime numbers count++; //Reset //isFlag = true; } System.out.println("The number of prime numbers is"+count); long end = System.currentTimeMillis(); System.out.println("The time taken is"+(end - start)); } }
4.5 break and continue structures
1. Use of break
- The break statement is used to terminate the execution of a statement block
2. Use of continue
- continue statement
- continue can only be used in a loop structure
- The continue statement is used to skip one execution of its circular statement block and continue the next cycle
- When a continue statement appears in the body of a multi-level nested loop statement, a label can indicate which level of loop to skip
3. Use of return
- Return: it is not specifically used to end a loop. Its function is to end a method. When a method executes a return statement, the method will be terminated.
- Unlike break and continue, return directly ends the entire method, no matter how many layers of loops the return is in.
4. Description of special process control statement
- break can only be used in switch statements and loop statements.
- continue can only be used in loop statements.
- The functions of the two are similar, but continue is to terminate this cycle, and break is to terminate this layer of cycle.
- There can be no other statements after break and continue, because the program will never execute the subsequent statements.
- The label statement must immediately follow the head of the loop. Label statements cannot be used before acyclic statements.
- Many languages have goto statements. Goto statements can transfer control to any statement in the program at will, and then execute it. But it makes the program error prone. break and continue in Java are different from goto.
package day05; /* break And countinue keywords Scope of use Functions used in the loop (different points) Same point break: switch-case End current cycle Cannot declare an execution statement after a keyword In cyclic structure countinue: In cyclic structure End the current cycle Cannot declare an execution statement after a keyword */ public class BreakContinueTest { public static void main(String[] args) { for (int i=1; i<=10; i++) { if (i%4==0) { break; } System.out.println(i); } System.out.println(); for (int i=1; i<=10; i++) { if (i%4==0) { continue; } System.out.println(i); } System.out.println(); label:for (int i=1; i<=4; i++) { for (int j=1; j<=10; j++) { if (j%4==0) { //break;// By default, the layer closest to this keyword will jump out of the loop //break label;// Ends a layer of circular structure with a specified identity continue label;//End the single cycle of the one-layer cycle structure with the specified ID } System.out.println(j); } } } }