Java process control

Keywords: Java

Program flow control

Sequential structure

  • The program is executed line by line from top to bottom without any judgment and jump.
  • Without any process control, the program always executes each statement from top to bottom.

Branching structure

  • Selectively execute a piece of code according to conditions.
  • There are two branch statements: if else and switch case.

If else structure

  • else is optional
  • For multiple conditional expressions, there is a "mutually exclusive" relationship (or a relationship without intersection).
  • If there is an intersection relationship between multiple conditional expressions, you need to consider which structure should be declared on it according to the actual situation.
  • If there is an inclusion relationship between multiple conditional expressions, you must first deal with the case with a small inclusion range, otherwise the case with a small range will not have a chance to run.
  • If else structures can be nested.

if statements have three formats

if(Conditional expression){
	Execute expression;
}

if(Conditional expression){
	Execute expression 1;
}
else{
	Execute expression 2;
}

if(Conditional expression){
	Execute expression 1;
}
else if{
	Execute expression 2;
}
... ...
else{
	Execute expression n;
}

Specific examples

class IfTest{
	public static void main(String[] args){
		//Format 1
		int hearBeats = 78;
		if(hearBeats < 60 || hearBeats > 100){
			System.out.println("Further inspection is required!");
		}
		System.out.println("End of inspection");
		
		//Format 2
		int age = 23;
		if(age < 18){
			System.out.println("You can't get married");
		}else{
			System.out.println("You can get married");
		}
		
		//Format 3
		if(age < 0){
			System.out.println("The data you entered is illegal!");
		}else if(age < 18){
			System.out.println("Youth");
		}else if(age < 35){
			System.out.println("Young adults");
		}else if(]age < 60){
			System.out.println("Middle age");
		}else{
			System.out.println("Old age");
		}
	}
}
  • Multiple lines of code in curly brackets after if, else if and else are called code blocks. A code block is usually executed as a whole (unless return, break, continue and other keywords are encountered during operation, or exceptions are encountered.)
  • Else means "otherwise". Else itself is a condition, which is why the code blocks behind if and else are collectively referred to as conditional executors. The implicit condition of else is to negate the previous conditions.

Switch case structure

switch(expression){
	case Constant 1:
		Statement 1;
		//break;
	case Constant 2:
		Statement 2;
		//break;
	... ...
	case constant N:
		sentence N ;
		//break;
	default;
		sentence;
		//break;
}

  • Match the constants in each case in turn according to the values in the switch expression. Once the match is successful, it enters the corresponding case structure and calls its execution statement. After calling the execution statement, continue to execute the execution statements in other case structures down until the break keyword or program termination is encountered.
  • In the switch case structure, once the break keyword is executed, it will jump out of the switch case structure.
  • switch structure expression can only be byte, short, char and int integer types, enumeration type and String type (allowed from Java 7), one of the data types in 6, and cannot be boolean type.
  • Only constants can be declared after case, and ranges cannot be declared.
  • The break keyword is optional.
  • default is equivalent to else in if else.

example

String season = "summer";
switch(season){
	case"spring":
		System.out.println("spring");
		break;
	case"summer":
		System.out.println("summer");
		break;
	case"autumn":
		System.out.println("autumn");
		break;
	case"winter":
		System.out.println("winter");
		break;
	default:
		System.out.println("Season input error!");
		break; 
}

Examples about break

//Input "month" and "day" of 2019 from the keyboard, and the date required to be entered through the program is the day of 2019

import java.util.Scanner;
class SwitchCaseTest2{
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		System.out.println("Please enter 2019 month: ");
		int month = scanner.nextInt();
		System.out.println("Please enter 2019 day: ");
		int day = scanner.nextInt();
		
		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);
	}
}

Note break is optional in switch case

  • Any structure using switch case can be converted to if else. On the contrary, it does not hold.
  • When writing a branch structure, we prefer to use switch case when we find that we can use both switch case (at the same time, there are not too many values of expressions in switch) and if else. Reason: the execution efficiency of switch case is slightly higher.

Cyclic structure

  • When certain conditions are met, the function of specific code is executed repeatedly.
  • There are three loop statements: for, while and do while.


Note: JDK1.5 provides a for each loop to easily traverse sets and array elements.

Four elements of circular structure

① Initialization condition
② Loop condition (condition is boolean type)
③ Circulatory body
④ Iterative condition

Use of for loop structure

Structure of for loop

for(①;②;④){
	③
}

Execution process: ① - > ② - > ③ - > ④ - > ② - > ③ - > ④... - > ②

The two semicolons in the parentheses of the for loop are required. Initialization statements, loop conditions and iteration statements can be omitted. If the loop condition is omitted, the loop condition defaults to true and an endless loop will be generated.

public class Text09 {	public static void main(String[] args) {        //Three parts of the for loop are omitted, and the loop condition is always true 		 for (;;) { 			 System.out.println(123); 		}	}

output

123

123

...

When using the for loop, you can also define the initialization condition outside the loop and put the loop iteration statement inside the loop. This method is similar to the following while loop.

public class Text10 {	public static void main(String[] args) {		int i = 0;		for (;i<3;) {			System.out.println(i);			i++;		}		System.out.println("End of cycle");	}

Output:

0
1
2
End of cycle

for loop example

/*Title: 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*/import java.util.Scanner;class ForTest{	public static void main(String[] args){		Scanner scan = new Scanner(System.in);				System.out.println("Please enter the first integer:");		int m = scan.nextInt();		int m = scan.nextInt();				System.out.println("Please enter the first integer:");		int m = scan.nextInt();				//Gets the maximum common divisor of two numbers 		 int min = (m <= n)? m : n; 		 for(int i = min;i >= 1;i--){ 			 if(m % i == 0&& n %i == 0){ 				 System.out.prinyln("the maximum common divisor is:" + I); 				 Break; / / once the break is executed in the loop, the loop will jump out 			}		}				// Gets the least common multiple of two numbers 		 int max = (m >=n)? m : n; 		 for(int i = max;i <= n*m;i++){ 			 if(m % i == 0&& n %i == 0){ 				 System. Out. Println ("the least common multiple is:"); 				 break; 		}	}}/* Output all 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*/import java.util.Scanner;class ForTest2{ 	 public static void main(String[] args){ 		 int a,b,c,s; 		 for(i = 0;i <= 100;i++){ 			 c=i%10; 			 b=(i/10)%10; 			 a=i/100; 			 if(Math.pow(a,3)+Math.pow(b,3)+Math.pow(c,3)==i) 		}		 System.out.println(""+i); 	}}

while Loop

① Initialization condition
② Loop condition (condition is boolean type)
③ Circulatory body
④ Iterative condition

while loop structure

①while(②){	③;	④;}

Execution process: ① - > ② - > ③ - > ④ - > ② - > ③ - > ④... - > ②

explain

  • When writing a while loop, be careful not to lose the iteration condition. Once lost, it may lead to an endless loop!
  • When writing programs, we should avoid dead cycles, and the algorithm should be limited.
  • for loop and while loop can be converted to each other
    Difference: the scope of the initialization condition part of the for loop and the while loop is different.
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++; 		}		// After the while loop is out, I can still be called (the difference between a for loop and a while loop) 		 System.out.println(i);// i=101 	}}

do-while Loop

① Initialization condition
② Loop condition (condition is boolean type)
③ Circulatory body
④ Iterative condition

Do while loop structure

①do{	③;	④;}while(②);

Execution process: ① - > ③ - > ④ - > ② - > ③ - > ④... - > ②

explain:

  • The do while loop executes the loop body at least once
  • In development, for and while loops are used more and do while is used less
class DoWhileTest{	public static void main(String[] args){		//Traverse even numbers within 100 and calculate the sum of all even numbers and the number of even numbers 		 int num = 1; 		 int sum = 0;// Record sum 		 int count = 0;// Number of records 		 do{ 			 if(num % 2 == 0){ 				 System.out.println(num); 				 sum += num; 				 count++; 			}			 num++; 		} while(num <= 100); 	}	 System.out.println("sum is:" + sum "); 	 System.out.println("number is:" + count);}

Use of while(true) structure

Title: read an uncertain number of integers from the keyboard, judge the number of positive and negative numbers, and enter 0 to end the program

import java.util.Scanner;class ForWhileTest{	public static void main(String[] args){				Scanner scan = new Scanner(System.in);				int positiveNumber = 0;    //Record the number of positive numbers 		 int negativeNumber = 0; / / record the number of negative numbers 				 while(true){                     //for(;;) 			 int number = scan.nextInt(); 						// Judge the positive and negative of number 			 if(number >0 ){ 				 positiveNumber++; 			} else if(number < 0){ 				 negativeNumber++; 			} else{ 				 break; 			}		}		 System.out.println("enter positive numbers:" + positiveNumber); 		 System.out.println("input negative numbers:" + negativeNumber); 	}}

explain:

  • Structure that does not limit the number of times in the loop condition part: for(;;) or while(true)
  • How the cycle ends:
    1. The loop condition part returns false
    2. In the loop body, execute break
  • It is recommended not to change the value of the loop variable in the loop body, otherwise it will increase the possibility of error. (if it needs to be modified, redefine a temporary variable)

be careful

The for loop is different from while and do while: the loop iteration statements of while and do while follow the loop body. If the loop body cannot be fully executed (such as ending the loop with continue) , the loop iteration statement will not be executed. However, the iteration statement of the for loop is not placed with the loop body, so the iteration statement will be executed whether or not the continue statement is used to end the loop.

Nested loop

Use of nested loops

  • Declaring A loop structure A in the loop body of another loop structure B constitutes loop nesting
  • The outer loop is loop structure B, and the inner loop is loop structure A
  • The inner loop structure is traversed once, which is only equivalent to the execution of the outer loop body once
  • The outer loop is executed m times and the inner loop is executed n times. At this time, the loop body of the inner loop is executed m*n times in total.

Nested loop connection

multiplication table
1 × 1 = 1
2 × 1 = 2 2 × 2 = 4
...
9 × 1 = 9 ... 9 × 9 = 81

class NineTable{	public static void main(String[] args) {		for(int i = 1;i <= 9;i++){			for(int j = 1;j <= i;j++){				System.out.print(i+"×"+j+"="+(i*j));			}			System.out.println();		}			}}

All prime numbers within 100
Prime: prime, a natural number that can only be divided by 1 and itself

class PrimeNumberTest{   //Prime number 	 p 	 public static void main(String[] args) { 								 For (int i = 2; I < = 100; I + +) {/ / traverse natural numbers within 100 			 boolean isFlag = true; 			 For (int j = 2; J < I; j + +) {/ / and I do division 								 if(i % j == 0) { 					 isFlag = false; 				}							}			 if(isFlag == true) { 				 System.out.println(i); 				}		}			}}

optimization algorithm

public class PrimeNumberTest1 {	public static void main(String[] args) {				//Get the distance between the current time and 1970-01-01 00:00:00 		 long start = System.currentTimeMillis(); 				 int count = 0; 				 For (int i = 2; I < = 10000; I + +) {/ / traverse natural numbers within 100 			 boolean isFlag = true; 			 For (int, j = 2; J < = math.sqrt (I); j + +) {/ / and I do division 								 if(i % j == 0) { 					 isFlag = false; 					 break; / / optimization 1: only valid for natural numbers that are not prime numbers 				}							}			 if(isFlag == true) { 				// System.out.println(i); 				 count++; 			}		}		// Get the distance between the current time and 1970-01-01 00:00:00 		 long end = System.currentTimeMillis(); 		 System.out.println(count); 		 System.out.println(end-start); 	}}

How to get variables from the keyboard

Specific implementation steps:

  1. Guide Package: import java.util.Scanner;
  2. Instantiation of Scanner: Scanner scan = new Scanner(System.in);
  3. Call the relevant methods of the Scanner class to obtain variables of the specified type.

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, resulting in the termination of the program.

import java.util.Scanner;class ScannerTest{	public static void main(String[] args){		Scanner scan = new Scanner(System.in);		System.out.println("Please enter any integer:");		int num = scan.nextInt();		System.out.println(num);	}}
  • For char type acquisition, Scanner does not provide relevant methods, and can only obtain one string.

How to get a random number

Formula: [a,b] (int)(Math.random() * (b - a + 1) + a);

//Obtain the random number of 10-90, int value = (int)(Math.random() * 90 + 10);

Gets the character at the corresponding position of the string

String gender = scan.next();//Input the string char genderChar = gender.charAt(0); / / obtain the character at position 0, which is actually the first character of the input string System.out.println(genderChar); / / output the obtained character

Posted by DBookatay on Sat, 18 Sep 2021 16:09:38 -0700