Java basic grammar: day03 flow control []

First, the flow statement 

Outline

During a program execution, the order of execution of the statement of the program is the result of a direct impact. That is, the flow of the program have a direct impact on operating results. So, we have to understand the flow of execution for each statement.

And, many times we want to achieve our functions to be performed by the execution order control statements.

 Sequence Structure

public class Demo01Sequence {
	public static void main(String[] args) {
		System.out.println ( "a nice day");
		System.out.println ( "very sunny");
		System.out.println ( "We do not have classes in the afternoon");
		System.out.println ( "This is really very cool");
	}
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=53969:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo01Sequence
the weather is nice today
Very sunny
We did the afternoon class
This is indeed very cool

Process finished with exit code 0

Second, determine the sentence

 1, the judge sentences 1 - if

1, the statement format

if (relational expression) {
   Statement body;  

2, the implementation process

  1. First, determine the relationship between the expression to see the result is true or false
  2. If the statement is true on the implementation of the body
  3. If false statement is not executed body

3, the sample code

// single if statement
public class Demo02If {
	public static void main(String[] args) {
		System.out.println ( "Today the weather is good, is to pressure the road ...... suddenly found a happy place: Internet cafes");
		int age = 19;
		if (age >= 18) {
			System.out.println ( "into the cafe, began high!");
			System.out.println ( "met a group of pigs as teammates, began squalling.");
			System.out.println ( "feel uncomfortable, leave the checkout.");
		}
		System.out.println ( "home for dinner");
	}
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=54040:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo02If
Today the weather is good, is to pressure the road ...... suddenly found a happy place: the Internet
Into the cafe, began high!
Met a group of pigs as teammates, he began to swear.
Feel uncomfortable, leave the checkout.
Home for dinner

Process finished with exit code 0

2, the judge sentences 2 - if ... else

1, the statement format

if (relational expression) {
   Statement 1;  
}else {
   Statement 2;  
}

2, the implementation process

  1. First, determine the relationship between the expression to see the result is true or false
  2. If the statement is true on the implementation of 1
  3. If false statement on the implementation of 2

3, the sample code

package day03;

public class Demo03IfElse {
    public static void main(String[] args) {
        int num = 666;

        if (num% 2 == 0) {// if the remainder can be divided by 2 is 0, indicating an even number
            System.out.println("偶数");
        } else {
            System.out.println("奇数");
        }
    }
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=54094:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo03IfElse
even

Process finished with exit code 0

 3, judge sentences 3 - if..else if ... else

1, the statement format

if (judgment condition 1) {
   Statement 1 is executed;  
} Else if (determination condition 2) {
   Execute the statement 2;  
}
...
} Else if (condition determination n) {
  Execute the statement n;   
} else {
   Executing the statement n + 1;  
}

2, the implementation process

  1. First, determine the relationship between the expression 1 to see the result is true or false
  2. If the statement is true on the implementation of 1
  3. If it is false to continue to determine the relationship between the expression 2 to see the result is true or false
  4. If the statement is true on the implementation of 2
  5. If it is false to continue to determine the relationship between the expression ... see the result is true or false
  6. If there is no relationship between the expression is true, then the statement is executed body n + 1.

3, the sample code

Relations // x and y satisfy the following:
// If x> = 3, then y = 2x + 1;
// If -1 <x <3, then y = 2x;
// If x <= -1, then y = 2x - 1;
public class Demo04IfElseExt {
	public static void main(String[] args) {
		int x = -10;
		int y;
		if (x >= 3) {
			y = 2 * x + 1;
		} else if (-1 < x && x < 3) {
			y = 2 * x;
		} else {
			y = 2 * x - 1;
		}
		System.out.println ( "The result is:" + y);
	}
} 

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=54210:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo04IfElseExt
The result: -21

Process finished with exit code 0

4, statement Exercise

1, demand:

Specifies the test scores to determine student grades
90-100 Excellent
80-89 Good
70-79 Good
60-69 pass
60 or less fail

2, implementation code

public class Demo05IfElsePractise {
	public static void main(String[] args) {
		int score = 120;
		if (score >= 90 && score <= 100) {
			System.out.println ( "excellent");
		} else if (score >= 80 && score < 90) {
			System.out.println("好");
		} else if (score >= 70 && score < 80) {
			System.out.println("良");
		} else if (score >= 60 && score < 70) {
			System.out.println ( "pass");
		} else if (score >= 0 && score < 60) {
			System.out.println ( "failed");
		} Else {// handled separately pathological case outside the boundary
			System.out.println ( "data error");
		}
	}
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=54256:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo05IfElsePractise
data error

Process finished with exit code 0

  int score = 99;

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=54284:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo05IfElsePractise
excellent

Process finished with exit code 0

5, if the statement and the ternary operator exchange

1, demand:

Title: ternary operator and if-else statement standards were achieved: maximum value among the two numbers

2, implementation code

public class Demo06Max {
	public static void main(String[] args) {
		int a = 105;
		int b = 20;
		
		// first the ternary operator
		// int max = a > b ? a : b;
		
		// using the if statement today
		int max;
		if (a > b) {
			max = a;
		} else {
			max = b;
		}
		
		System.out.println ( "maximum value:" + max);
	}
}

operation result

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=54352:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo06Max
Maximum: 105

Process finished with exit code 0

Third, the select statement

 1, select statement --switch

1, the statement format

switch (expression) {
  case a constant value:
    Statement 1;
    break;
  case 2 constant value:
    Statement 2;
    break;
  ...
  default:
    Body statement n + 1;
    break;
}

2, the implementation process

  1. First, calculate the value of the expression
  2. Secondly, compare and order case, if there is a corresponding value, will execute the corresponding statement in the process of implementation, it encounters a break will end.
  3. Finally, if the case were all expressions and values ​​do not match, it will execute the default statement body part, and the program ends off.

3, the sample code

public class Demo08SwitchNotice {
	public static void main(String[] args) {
		int num = 2;
		switch (num) {
			case 1:
				System.out.println ( "Hello");
				break;
			case 2:
				System.out.println ( "I'm good");
				// break;
			case 3:
				System.out.println ( "Hello everybody");
				break;
			default:
				System.out.println ( "he is good, I am fine.");
				break;
		} // switch
	}
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=54463:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo08SwitchNotice
I'm good
Hello everyone

Process finished with exit code 0

4 Notes

1. The plurality of values ​​that follow the case can not be repeated.

2. switch parentheses behind which only the following data types:

  1. Basic data types: byte / short / char / int
  2. Reference data types: String string, enum enumeration

3. switch statement format can be very flexible: before and after the order can be reversed, and break statement can also be omitted. "Which case match on a position from which to perform downward until it encounters a break or a whole until the end."

2, case of penetration

In a switch statement, if the latter case is not writing break, will appear penetration phenomenon, which is not a value judgment in the case, run directly back, until it encounters a break, or the end of the whole switch

public static void main(String[] args) {
  int i = 5;
  switch (i){
    case 0:
      System.out.println ( "execution case0");
      break;
    case 5:
      System.out.println ( "execution case5");
    case 10:
      System.out.println ( "execution case10");
    default:
      System.out.println("执行default");
  }
}

This program, after performing case5, because there is no break statement, the program will always go back, not in judgment case, it will not bother break, finished directly run the entire switch.

Because of penetrating case, therefore beginners when writing switch statement, you must write on the break.

Chapter IV loop

1, loop 1 - for

The basic components of the cyclic structure, can generally be divided into four parts:

1. Initialize the statement: originally performed at the beginning of the cycle, and the only time only.
2. conditional: if true, the loop continues; if not true, the loop exits.
3. The body of the loop: duplicate content to do several line statement.
4. Stepping statement: mop-up work should be carried out after each cycle of every executed once after the end of the cycle.

1, the statement format

for (initialization expression ①; ② Boolean expression; expression step ④) {
③ loop        
}

2, the implementation process

The order of execution: ①②③④> ②③④> ②③④ ... ② so far satisfied.
① responsible for completing the loop variable initialization
② responsible for determining whether the loop condition is not satisfied out of the loop
statements execute specific ③
④ After cycling, cycling conditions change of variables involved

3, the sample code

public class Demo09For {
	public static void main(String[] args) {
		for (int i = 1; i <= 5; i++) {
			System.out.println ( "I're wrong forgive me!!" + I);
		}
		System.out.println ( "program stop");
	}
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=54743:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo09For
I was wrong! please forgive me! 1
I was wrong! please forgive me! 2
I was wrong! please forgive me! 3
I was wrong! please forgive me! 4
I was wrong! please forgive me! 5
The program stops

Process finished with exit code 0

2, loop 2 - while

1, the statement format

① initialization expression
  while (Boolean expression ②) {
    ③ loop
    Stepping expression ④
}

2, the implementation process

The order of execution: ①②③④> ②③④> ②③④ ... ② so far satisfied.
① responsible for completing the loop variable initialization.
② responsible for determining whether the loop condition is not satisfied out of the loop.
③ specific statements executed.
After ④ cycle, changes in the loop variable.

3, the sample code

public class Demo10While {
	public static void main(String[] args) {
		for (int i = 1; i <= 5; i++) {
			System.out.println ( "I're wrong!" + I);
		}
		System.out.println("=================");
		
		int i = 1; // 1. initializer
		while (i <= 5) {// 2. Analyzing conditions
			System.out.println ( "I're wrong!" + I); // 3. loop
			i ++; // 4. Statement step
		}
	}
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=55015:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo10While
I was wrong! 1
I was wrong! 2
I was wrong! 3
I was wrong! 4
I was wrong! 5
=================
I was wrong! 1
I was wrong! 2
I was wrong! 3
I was wrong! 4
I was wrong! 5

Process finished with exit code 0

 3, loop 3 - do ... while1, the statement format

1, the statement format

① initialization expression
    do{
    ③ loop
    Stepping expression ④
} While (Boolean expression ②);

2, the implementation process

The order of execution: ①③④> ②③④> ②③④ ... ② so far satisfied.
① responsible for completing the loop variable initialization.
② responsible for determining whether the loop condition is not satisfied out of the loop.
③ execution of specific statements
④ After the loop, the loop variable changes

3, the sample code

package day03;

public class Demo11DoWhile {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println ( "forgive you now get up on the ground strange cool!!!" + I);
        }
        System.out.println("===============");

        int i = 1; // 1. initializer
        do {
            System.out.println ( "forgive you now get up on the ground strange cool!!!" + I); // 3. loop
            i ++; // 4. Statement step
        } While (i <= 3); // 2. Analyzing conditions
    }
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=55124:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo11DoWhile
Forgive you anyway! Get up! On the ground strange cool! 1
Forgive you anyway! Get up! On the ground strange cool! 2
Forgive you anyway! Get up! On the ground strange cool! 3
Forgive you anyway! Get up! On the ground strange cool! 4
Forgive you anyway! Get up! On the ground strange cool! 5
===============
Forgive you anyway! Get up! On the ground strange cool! 1
Forgive you anyway! Get up! On the ground strange cool! 2
Forgive you anyway! Get up! On the ground strange cool! 3

Process finished with exit code 0

Statement Exercise

Topic: find the even and between 1-100.

Ideas:

1. Since the range has been determined is between 1-100, then I went from 100 up to 1,2,3 ...... so many numbers one by one check.
2. A total of 100 numbers, not all numbers can be used. If necessary to use an even number, decision making (if statement) the even: NUM% 2 == 0
3. requires a variable used for accumulating operation. It is like a piggy bank.

Implementation code

package day03;

public class Demo12HundredSum {
    public static void main(String[] args) {
        int sum = 0; // for accumulating piggy bank

        for (int i = 1; i <= 100; i++) {
            if (i% 2 == 0) {// if it is an even number
                sum += i;
            }
        }
        System.out.println ( "The result is:" + sum);
    }
}

operation result

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=55210:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo12HundredSum
The result: 2550

Process finished with exit code 0

4, loop differences

1. If the conditional never been satisfied, then the for loop and while loop will be executed zero times, but do-while loop will execute at least once.

2. for loop variable in parentheses among definition, only the inner loop can be used. while loops and do-while loop initialization statement already outside, so after the cycle can continue to use it.

Sample Code

package day03;

public class Demo13LoopDifference {
    public static void main(String[] args) {
        for (int i = 1; i < 0; i++) {
            System.out.println("Hello");
        }
        // System.out.println (i); // this line is wrong wording! Because the variable i is defined within a for loop parentheses, only for circulation to their own use.
        System.out.println("================");

        int i = 1;
        do {
            System.out.println("World");
            i++;
        } while (i < 0);
        // now is beyond the scope of the do-while loop, we can still use the variable i
        System.out.println(i); // 2
    }
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=55277:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo13LoopDifference
================
World
2

Process finished with exit code 0

5, out of the statement

There are keyword usage break Two common:

1. can be used in a switch statement which, if implemented, the entire switch statement ends immediately.
2. The loop can also be used in which, if implemented, the entire loop end immediately. Break the cycle.

Sample Code

package day03;

public class Demo14Break {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            // If you want to start from the 4th, follow all do not, we must break the cycle
            if (i == 4) {// if the current is the fourth
                break; // then break the whole cycle
            }
            System.out.println("Hello" + i);
        }
    }
}

  Export

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=55344:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo14Break
Hello1
Hello2
Hello3

Process finished with exit code 0

About cycle options, there is a small suggestion: Those who determine the number of scenes for multi-loop; otherwise multi-while loop.

Another loop control statement is the continue keyword.

Once executed, immediately skip the remaining contents of the current cycle, the next cycle to start immediately.

Sample Code

package day03;

public class Demo15Continue {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 4) {// if the current is the fourth layer
                continue; // current cycles are skipped and immediately start the next (fifth layer)
            }
            System.out.println (i + "to the layer.");
        }
    }
}

operation result

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=55344:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo14Break
Hello1
Hello2
Hello3

Process finished with exit code 0

Fifth, the expansion of knowledge

 1, the cycle of death

Never not stop the cycle, called an infinite loop.

1, the statement format

Death cycle of a standard format:
while (true) {
	Loop
}

2, the sample code

package day03;

public class Demo16DeadLoop {
    public static void main(String[] args) {
        while (true) {
            System.out.println("I Love Java!");
        }

        // System.out.println("Hello");
    }
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=55737:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo15Continue

I Love Java!
I Love Java!
I Love Java!
...
Endlessly down

In the later development, there will be an infinite loop use scenarios, such as: we need to read the input entered by the user, but how much data the user input is not clear, can only use the death cycle, when the user does not want to enter your data,
you can end the cycle, and how to end an infinite loop it, you need to use to jump out of the statement.

2, nested loops

The so-called nested loops, a loop means is another circulation loop. For example, there is also a for loop for loop is nested loops. The total number of cycles * = number of cycles within the outer loop

1, the statement format

for (initialization expression ①; ② cycling conditions; stepping expression ⑦) {
    for (initialization expression ③; ④ cycling conditions; stepping expression ⑥) {
       Execute the statement ⑤;  
    }
} 

2, the implementation process

Execution order: ①②③④⑤⑥> ④⑤⑥> ⑦②③④⑤⑥> ④⑤⑥
outer loop once, the cycle several times.
Skipping example: total jump 5 groups of 10 hops. Group 5 is an outer loop, the inner loop is 10.

3, the sample code

public static void main(String[] args) {
    // rectangular 5 * 8 * print line number 5, for each row of 8
    // 5 the outer loop, the inner loop 8
    for(int i = 0; i < 5; i++){
        for(int j = 0; j < 8; j++){
            // does not wrap print asterisk
            System.out.print("*");
        }
        After printing cycle within eight asterisks // needs a line feed
        System.out.println();
}

operation result:

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\lib\idea_rt.jar=56980:C:\Program Files\JetBrains\IntelliJ IDEA 2019.2\bin" -Dfile.encoding=UTF-8 -classpath C:\java\JavaApps\out\production\JavaApps day03.Demo16DeadLoop
********
********
********
********
********

Process finished with exit code 0

Guess you like

Origin www.cnblogs.com/luoahong/p/12597228.html