Java foundation - structured programming

Keywords: Java Programming less

Structured process design

The principle of structured programming can be expressed as: program = (algorithm) + (data structure).
The three basic structures of structured programming are sequence structure, selection structure and cycle structure.

Sequential structure

Sequential structure means that the operations in a program are performed in the order in which they appear.
The basic structure of Java is sequential structure. Unless otherwise specified, it is executed one sentence at a time in order. It is the simplest algorithm structure.

Statements and statements are carried out in order from top to bottom. It is composed of several processing steps that are executed in turn. The order structure is a basic algorithm structure that any algorithm can not do without.

package cn.ara.structure;

//Sequence structure demonstration
public class Order {
    public static void main(String[] args) {
        System.out.println("111");
        System.out.println("222");
        System.out.println("333");
        System.out.println("444");
        System.out.println("555");
    }
}

In this program, the code is executed sentence by sentence from top to bottom, and the printing results are as follows:
111
222
333
444
555
It is executed according to the sequence of the code we have written. This is the sequence structure of the program.

Selection structure

The selection structure indicates that the processing step of the program has branches, and it needs to select one of the branches according to a specific condition for execution.

if selection structure

if single selection structure

When we need to judge whether a thing is feasible or not, and if it is feasible, we will execute some statements, we will use if single choice statement to express, the syntax is as follows:

If (Boolean expression){
	//Statement to execute if the value of a Boolean expression is true
}

//Declare Scanner object
Scanner scanner = new Scanner(System.in);

//Judge whether the input is an integer
if (scanner.hasNextInt()) {
    int i = scanner.nextInt();
    System.out.println("The integer you entered is:" + i);
}

//Close input flow object
scanner.close();

For the above code, when we input integer data, the statement in the if structure will be executed, otherwise, the statement in the if structure will not be executed.

if double selection structure

When we need to judge whether a thing is feasible, if it is feasible, we need to execute a paragraph of statement, if it is not feasible, we need to execute another paragraph of statement, we will use if double choice statement to express, the syntax is as follows:

if(Boolean expression){
	//Statement to execute if the value of a Boolean expression is true
} else {
	//Statement to execute if the value of a Boolean expression is false
}

//Declare Scanner object
Scanner scanner = new Scanner(System.in);

//Judge whether the input is an integer
if (scanner.hasNextInt()) {
    int i = scanner.nextInt();
    System.out.println("The integer you entered is:" + i);
} else {
    System.out.println("You are not entering an integer");
}

//Close input flow object
scanner.close();

Or the above program, we have made some improvements. When the input is an integer, the output integer you input is: (the input integer), otherwise, the output integer you input is not an integer

if multi selection structure

When we need to judge whether a thing meets many different conditions, we need to execute statement one if condition one is satisfied, statement two if condition two is satisfied, and statement three if condition three is satisfied We will use the if multiple choice statement to express, the syntax is as follows:

if(condition1){
	//Execute when condition 1 is satisfied
}else if(condition2){
	//Execute when condition 2 is satisfied
}else if(condition3){
	//Execute when condition 3 is satisfied
}
...
else{
	//If none of the above conditions are met
}

//Declare Scanner object
Scanner scanner = new Scanner(System.in);

System.out.println("Please enter your score(0-100): ");

//Get input score
int score = scanner.nextInt();

//Judgement score
if (score <= 100 && score >= 90) {
    System.out.println("excellent");
} else if (score < 90 && score >= 80) {
    System.out.println("good");
} else if (score < 80 && score >= 60) {
    System.out.println("pass");
} else if (score < 60 && score >= 0) {
    System.out.println("Fail,");
} else {
    System.out.println("Illegal achievements");
}

//Close input stream
scanner.close();

The program here will execute different statements according to the different data entered by the user.

if statements can be nested. Pay attention to the overall structure of the program when nesting. {and} need to correspond. The following code is an improved version of the above code:

//Declare Scanner object
Scanner scanner = new Scanner(System.in);

System.out.println("Please enter your score(0-100): ");

//Judge whether the input is legal
if (scanner.hasNextInt()) {
    //Get input score
    int score = scanner.nextInt();

    //Judgement score
    if (score <= 100 && score >= 90) {
        System.out.println("excellent");
    } else if (score < 90 && score >= 80) {
        System.out.println("good");
    } else if (score < 80 && score >= 60) {
        System.out.println("pass");
    } else if (score < 60 && score >= 0) {
        System.out.println("Fail,");
    } else {
        System.out.println("Illegal achievements");
    }
}else{
    System.out.println("Please input correct data");
}
//Close input stream
scanner.close();

switch selection structure

The switch case statement in Java determines whether a variable is equal to a certain value in a series of values. Each value is called a branch. Its basic structure is:

switch(Expression){
	case value1:
		//Statement 1
		break;//Optional
	case value2:
		//Statement 2
		break;//Optional
	...
	case valuen:
		//Statement n
		break;//Optional
	default: //Optional
		//Statement n+1
}

Expression values support char, byte, short, int and their wrapper classes Character, byte, short, Integer, and String (String types are supported since Java SE 7), enum.

The value value in the case statement should be the same as that of the corresponding switch statement. When the value of the switch expression "hits" the value of a case statement, the code in the corresponding case statement will be executed, and then the switch statement will be executed in sequence until the break statement appears or the switch statement ends.

The break statement means to end or abort. It means to end the switch statement in the switch statement. It will generally pair with case in the switch statement. If it is not matched, case penetration may occur.

The default statement does not require a value for the vault because it is executed only if its corresponding switch expression does not "hit" the case statement or "break" statement is not "encountered" after "hit".

char grade = 'A';

switch (grade) {
    case 'A': //Match to A execution
        System.out.println("excellent");
        break; //End switch statement
    case 'B': //Match to B execution
        System.out.println("good");
        break;
    case 'C': //Match to C execution
        System.out.println("pass");
        break;
    case 'D': //Match to D execution
        System.out.println("Fail,");
        break;
    default: //Execute when not matched
        System.out.println("Wrong level!");
}

The above code will execute different codes according to different grade values.

Case penetration: because after the switch expression hits the case statement, if it does not encounter the break statement later, it will execute according to the sequence structure, which is called case penetration (case penetration can be clearly observed by removing the break in the above code).

Cyclic structure

A loop structure means that a program repeatedly performs an operation or operations until a condition is true (or false).

while Loop

In Java, while is the most basic loop. Its structure is as follows:

Its Java syntax is:

While (Boolean expression){
	//Cycle content
}
  • As long as the value of the Boolean expression is true, this Boolean expression is a loop condition. As long as it always meets the condition, it will always loop.
  • Most of the time, the loop will end. We need to have a time when the expression is false.
int i = 1;
while (i <= 100) { //Execute when i is less than or equal to 100
    System.out.println(i);
    i++; //Self increment 
}

The above code is the cyclic structure of printing 1-100.

do while loop

The structure of do while is:

Its Java syntax is:

do{
	//Cyclic code
} while(Boolean expression);

The do while loop is similar to the while loop, but the only difference is that the do while loop executes the code at least once.

The difference between while and do while:

  • While is to judge first and then execute. do while is executed before judgment.

So do while executes the loop statement at least once.

int i = 0;

while (i < 0) {
    System.out.println(i);
    i++;
}

System.out.println("-------------");

do {
    System.out.println(i);
    i++;
} while (i < 0);

The implementation results are as follows:
-------------
0

We find that when does not execute the loop statement, but do while executes the loop statement once, which is the only difference between the two loops.

for cycle

for loop statement is a general structure supporting iteration, and it is the most effective and flexible loop structure.

Its syntax format is:

For (initialization statement; Boolean expression; update statement){
	//Loop statement
}

With the above flow chart, we know the execution flow of for loop. Here we use the example directly:

//Print integers from 1 to 100
for (int i = 1; i <= 100; i++) {
    System.out.println(i);
}

We can compare this code with the above while loop code and find that we use the for loop more succinctly.

After Java 5, an enhanced for loop mainly used for arrays or collections was introduced. Its syntax format is as follows:

For (declaration statement: traversal object){
	/ / code
}
  • Declaration statement: declare a new local variable. The type of the variable must match the type of the traversal object. Its scope is limited in the circular statement, and its value is equal to the value of the element at this time.
  • Traversal object: the variable name of the traversal object.
int[] array = {1, 2, 3};

for (int i : array) {
    System.out.println(i);
}

The code above is an enhanced for loop that traverses an array.

Since I chose the distance, what I left behind is only my back.

Published 16 original articles, won praise 1, visited 333
Private letter follow

Posted by spamoom on Fri, 31 Jan 2020 23:09:08 -0800