Control process
Java's control process is basically the same as C and C + +, except that goto statements can be used, but break statements may be tagged to achieve the purpose of jumping out of the inner layer. Tags can be placed in front of for or while. As follows:
- Package COM.ZJF;
- Import Java.io.Console;
- Import Java.util.Scanner;
- public class Test {
- Public static void Main (string[] args) {
- Outer: for (int i=0;i<5;i++) {
- for (int j=0;j<5;j++) {
- System.out.println ("i=" +i+ "j=" +j);
- if (j==3) {
- Break outer;
- }
- }
- }
- }
- }
Block scope:
Java is a block scope, and this is not the same as JS.
While loop
There are two types of while loops:
while ()
{
Do some thing
}
And
Do
{
Do some thing
}
while ()
For loop
for (initialize; condition to continue looping, update)
However, it is not recommended to have complex logic in a for loop, preferably a simple logic that determines the initialization and size of variables.
If you use floating-point numbers for detection in a loop, the result may be a dead loop. The following notation is a dead loop.
- Package COM.ZJF;
- public class Test {
- Public static void Main (string[] args) {
- For (double d = 0 D; d! = 1d;d+=0.1d)
- {
- System.out.println (d);
- }
- }
- }
Let's look at the output in a different way:
- Package COM.ZJF;
- public class Test {
- Public static void Main (string[] args) {
- For (double d = 0 D; d < 1d;d+=0.1d)
- {
- System.out.println (d);
- }
- }
- }
Output:
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
Multiple selection: switch statement
The switch statement can only work on shaping and enumeration. You cannot test a string, and you cannot test floating-point types.
Multiple case in a switch statement cannot be duplicated, so only one can be satisfied, and more than one cannot be satisfied. But if you don't add a break after each case, you'll go on to default. As follows:
- Package COM.ZJF;
- public class Test {
- Public static void Main (string[] args) {
- int i = 3;
- switch (i) {
- Case 1:
- SYSTEM.OUT.PRINTLN (1);
- Case 2:
- SYSTEM.OUT.PRINTLN (2);
- Case 3:
- SYSTEM.OUT.PRINTLN (3);
- Default:
- System.out.println ("default");
- }
- }
- }
Results:
3
Default
The author says in the book that it is possible to trigger multiple case branches, and if the statement does not add a break, then it will proceed to the next one, so try not to use break. There is no mistake in saying this, it is possible to trigger multiple branches, but the syntax requires that the key of the case cannot be duplicated, otherwise it will compile an error. So what is the purpose of Java's design, I guess, if you don't add break, every case goes to default, so you can add some common logic to the default.
Java BASIC program Structure design control Flow