In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly talks about "what are the flow control statements in JAVA". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the flow control statements in JAVA.
Like C and C++, Java procedures pass through the flow control system to carry out the sequence flow and complete a fixed task. Program flow is made up of Ruogan.
It's made up of two sentences. A statement can therefore be a single statement (such as cymbals;), or it can be enclosed in large brackets {}
Compound sentence.
Next, let's introduce the flow control statements in Java, including
1. Branch sentences: if-else, break, switch, return.
two。 Ring sentences: while, do-while, for, continue.
3. Sentences outside the case: try-catch-finally, throw
Finally, we briefly introduce the explanatory sentences.
§4.1 Branch statement
The branch sentence provides a control machine system, so that the holder of the sequence can skip some statements and transfer to the execution.
OK, a specific sentence.
4.1.1 item statement if-else.
The root of the if-else statement is determined to be true or false to carry out one of the two operations, and its form is:
If (boolean-expression)
Statement1
[else
Statement2;]
1. Boolean table boolean-expression is any form that returns Boolean data (this is better than the restriction of C, C++
Be strict.
two。 Every single statement must be followed by a semicolon.
3. The statement statement1,statement2 can be regarded as a compound sentence, which should be enclosed in large brackets {}. Suggestion on the sentence of singleness
Also enclosed in large brackets, this sequence is highly readable and is conducive to the expansion of the sequence (you can add new statements to it.
). {} there is no semicolon on the outside.
4. The else clause is optional.
5. If the value of the Boolean expression is true, the sequence holds the line statement1, otherwise the line st atement2.
A special form of 6.if-else sentence is:
If (expression1) {
Statement1
} else if (expression2) {
Statement2
}.
} else if (expressionM) {
StatementM
} else {
StatementN
}
@ @ [
The else clause cannot be used alone as a statement, it must be paired with if. Else is always paired with the nearest if
. You can change the pairing relationship by using braces {}.
7. For example:
Example 4.1 compare the size of two numbers and output them in order from smallest to largest.
@ @ [
Public class CompareTwo {
Public static void main (String args []) {
Double D1 / 23. 4
Double d2mm 35.1
If (D2 > = D1)
System.out.println (d2 + "> =" + D1)
Else
System.out.println (D1 + "> =" + D2)
}
}
The running result is:
C: > java CompareTwo
35.1 > = 23.4
Example 4.2 determine whether a certain year is a leap year.
The article of the leap year is one of the following two: ① is divisible by 4, but not divisible by 100; ② is divisible by 4 and can be divided by
100 divisible.
Public class LeapYear {
Public static void main (String args []) {
Int year=1989; / / method 1
If ((year%4==0 & & year0 records 0) | | (year%400==0))
System.out.println (year+ "is a leap year.")
Else
System.out.println (year+ "is not a leap year.")
Year=2000; / / method 2
Boolean leap
If (year% 4 years 0)
Leap=false
Else if (year0 years 0)
Leap=true
Else if (year% 400 years 0)
Leap=false
Else
Leap=true
If (leap==true)
System.out.println (year+ "is a leap year.")
Else
System.out.println (year+ "is not a leap year.")
Year=2050; / / method3
If (year%4==0) {
If (year0==0) {
If (year%400==0)
Leap=true
Else
Leap=false
} else
Leap=false
} else
Leap=false
If (leap==true)
System.out.println (year+ "is a leap year.")
Else
System.out.println (year+ "is not a leap year.")
}
}
The running result is
C: > java LeapYear
1989 is not a leap year.
2000 is a leap year.
2050 is not a leap year.
In this example, Fangfa 1 contains all the leap year items with a logic table, and Fangfa 2 uses the special statement of if-else.
Form, square method 3 passes the judgment of realizing the leap year by matching the if-else advance with large brackets {}. The big family can come according to the order of the root.
According to the comparison of these three methods, the combination and division of the body will be selected in different fields.
4.1.2 Multi-branch statement switch
The root of the switch statement holds one of several operations according to the value of the expression, and its same pattern is as follows:
Switch (expression) {
Case value1: statement1
Break
Case value2: statement2
Break
.
Case valueN: statemendN
Break
[default: defaultStatement;]
}
1. The expression can return the value of any simple single type (such as integer type, real type, character type) and make a multi-branch statement.
The value of the table dada return is compared to the value in each case clause. If the match works, then follow the sentence order after the case clause.
Column.
2. The value valueI in the case clause must be constant, and the values in all case clauses should be different.
3. The default clause is optional. The sequence holds the line when the value of the expression does not match the value in any of the case clauses
The sentence behind the default. If the value of the expression does not match the value in any of the case clauses and there is no default clause, the program
The preface does not do anything, but jumps directly out of the switch sentence.
The 4.break statement is used to make the program jump out of the switch statement, that is, to stop the execution of the switch statement, after the execution of a case branch.
. Because the case clause only serves as a sign, it is used to find a matching entrance and start the line from here, right behind.
Instead of line matching, the case clause is directly connected to the statement sequence that follows the line, so it should be used after each case branch.
Break comes to the end of the following case branch statement.
In some special cases, multiple different case values have to perform the same set of operations, which can be done without break.
When multiple statements are included in the 5.case branch, they can be enclosed without large brackets {}.
The function of the 6.switch sentence can be realized by using if-else, but in some situations, it makes the switch sentence more concise and readable.
, and the execution efficiency rate of the sequence is increased.
7. For example:
Example 4.3. The root prints out several paragraphs on a percentage scale according to the grades of the test scores.
Public class GradeLevel {
Public static void main (String args []) {
System.out.println ("* * first situation *")
Char grade= 'C '; / / normal use
Switch (grade) {
Case'A ': System.out.println (grade+ "is 85: 100")
Break
Case'B ': System.out.println (grade+ "is 70: 84")
Break
Case'C ': System.out.println (grade+ "is 60: 69")
Break
Case'D ': System.out.println (grade+ "is < 60")
Break
Default: System.out.println ("input error")
}
System.out.println ("* * second situation *")
Grade= 'A '; ∥ creat error without break statement
Switch (grade) {
Case'A ': System.out.println (grade+ "is 85: 100")
Case'B ': System.out.println (grade+ "is 70: 84")
Case'C ': System.out.println (grade+ "is 60: 69")
Case'D ': System.out.println (grade+ "is < 60")
Default: System.out.println ("input error")
}
System.out.println ("* * third situation *")
Grade= 'B '; ∥ several case with same operation
Switch (grade) {
Case'A ':
Case'B ':
Case'C ': System.out.println (grade+ "is > = 60")
Break
Case'D ': System.out.println (grade+ "is < 60")
Break
Default: System.out.println ("input error")
}
}
}
The running result is
C: > java GradeLevel
* first situation *
C is 60: 69
* second situation *
An is 8500100
An is 70,84
An is 60 / 69
An is < 60
Input error
* third situation *
B is > = 60
From this example, we can see the use of the break sentence.
4.1.3 break statement
1. In switch, the breaksentence is used to end the execution of the switch statement. To make an order from the first statement after a switch statement.
It's all right at the beginning.
two。 In Java, you can add a parenthesis to each code block, and a code block is usually a paragraph enclosed in large brackets {}
Code. The marked format is as follows:
BlockLabel: {codeBlock}
The second use case of a break sentence is to jump out of the block it refers to and hold it from the first statement immediately following the block.
All right. Its format is:
Break BlockLabel
For example:
A: {. / / Mark code block a
B: {. / / Mark code block b
C: {. / / Mark code block c
Break b
…… / / will not be executed
}
…… / / will not be executed
}
…… / execute from here
}
3. Unlike C and C++, there is no goto sentence in Java to realize the jump of meaning, because the readability of goto sentence breaks the bad sequence.
And the optimization of editing and translation. However, from the above example, we can see that Java uses break to realize some advantages unique to the goto sentence.
. If the label specified after break is not the number of a code block, but a statement, then the break is fully realized.
The power of goto. However, this kind of square use should be avoided. ? (to be continued)
4.1.4 return statement return
The return statement withdraws from the current square method, returns to the statement in which the square method is invoked, and follows the next sentence of the statement.
The sentence continues the execution of the sequence. There is the content of the related method, which we will discuss in detail in Chapter 6. Main () in the previous example is
It is a square method. There are two types of return sentences:
1.return expression
Return a value to the statement that calls the square method, and the numerical data type of the return value must be in harmony with the return value type in the square sound.
As soon as. It is possible to make the class type by using the strong class type conversion.
2.return
When the square method states that the return class type with void is empty, you should use this format, which does not return any value.
Return statements are often used at the end of a square aspect to get out of the square and return a value. In Java, the only one
When a return sentence is used in the middle of a square aspect, it will lead to errors in translation, because there will be some sentences that cannot be carried out. But...
By embedding return statements into certain statements (such as if-else), you can cause a program to exit when it does not hold all the statements in the line completion method.
For example:
Int method (int num) {
∥ return num; ∥ will cause compile time error
If (num > 0)
Return num
…… ∥ may or may not be executed
∥ depending on the value of num
§4.2 Ring statement
The function of the loop sentence is to repeat a code until the end of the loop, one by one.
It should include four parts:
1. Initialization part (initialization): some initial bars used to set up a loop, such as a counter to clear zero, etc.
two。 Loop body part (body): this is a code of an anti-repetitive loop, so it can be a single statement or a compound.
Sentence.
3. Iterative part (iteration): this is a statement that is knotted in front of the loop and held before the next opening of the loop. it is often used to cause.
Add or subtract 1 from the counter.
4. The final part (termination): it is usually a Boolean formula, and every time it is looped, the table should be evaluated for verification.
Whether it is full to follow the loop to end the piece.
The loop sentences mentioned in Java are: while sentence, do-while sentence and for sentence.
4.2.1while sentence
The while sentence actually shows the loop of "Dang type", and its general pattern is
[initialization]
While (termination) {
Body
[iteration;]
}
1. When the value of the Boolean expression (termination) is true, the statement in the line in large parentheses is held in a loop. And initialize the sum of parts
The iterative part is optional.
The 2.while sentence first calculates the final piece, and then carries out the statement in the loop when the piece is full. This is the "right type".
The special point of the ring.
4.2.2 do-while statement
The do-while statement implements a straight-to-type loop, which has the following general format:
[initialization]
Do {
Body
[iteration;]
} while (termination)
The 1.do-while statement begins with the loop, and then calculates the final stop. If the result is true, then follow the loop in the large brackets
The result of the Boolean expression is false.
two。 Different from the while sentence, the loop aspect of the do-while sentence is carried out at least once, which is the special point of the "straight to type" loop.
4.2.3 for statement
The for statement is also used to show the loop of the "dang type". Its general pattern is:
For (initialization; termination; iteration) {
Body
}
When the 1.for sentence is carried out, the initial operation is carried out first, and then it is judged whether the final stop is sufficient, and if it is satisfied, it will be followed.
The statement in the ring body is the last to hold the iterative part. After completing a loop, a new judgment is made to determine the final stop.
two。 It can be divided into a variable in the initialization part of the for sentence, and its scope is the whole for sentence.
The 3.for statement is often used to carry out the situation determined by the number of rings (such as the progressive operation of array elements), or it can also be based on the root loop.
The situation in which the number of degrees of the loop is uncertain.
4. The initialization part and the iterative part can be used to perform multiple operations with a tease sentence. The comma is used in the comma.
A separated sequence of sentences. For example:
For (iTun0, jaf10; I < j; iTunes, jmurf -) {
……
}
5. Initial, final and iterative parts can all be used as empty statements (but semicolons cannot be omitted), and all three are empty tenses and phases.
When in an infinite loop.
4.2.4 continue statement
The 1.continue sentence is used to tie up the loop this time, skipping the sentences in the middle and lower part of the loop that have not yet been carried out, and then moving on to the final stop.
The judgment of the document shall be made to determine whether it is to continue to follow the ring. For the for sentence, it is necessary to carry out the iteration before making the judgment of the final clause.
Sentence. Its format is:
Continue
two。 You can also use continue to jump to the outer loop indicated by parentheses, where the lattice is
Continue outerLable
For example:
Outer: for (int iTuno; I < 10; iTunes +) {∥ outer loop
For (int jacks 0; j < 20; jacks +) {∥ inner loop
If (j > I) {
……
Continue outer
}
……
}
……
}
In this example, when the bar is full of j > I, the program sequence jumps to the outer loop after the corresponding statement is executed, and the outer loop is carried out.
The iterative statement "icycle"; then begins the next loop.
4.2.5 give an example
The following examples are divided into while, do-while and for sentences to calculate the sum.
Public class Sum {
Public static void main (String args []) {
System.out.println ("* * while statement *")
Int initialization 10 ∥ sum up 0;
While (n > 0) {∥ termination
Sum+=n; ∥ body
∥ iteration
}
System.out.println ("sum is" + sum)
System.out.println ("* * do_while statement *")
Numb0; ∥ initialization
Sum=0
Do {
Sum+=n; ∥ body
∥ iteration
} while (n < = 10); ∥ termination
System.out.println ("sum is" + sum)
System.out.println ("* * for statement *")
Sum=0
For (int iTunes 1; I < = 10; iTunes +) {
∥ initialization,termination,iteration
Sum+=i
}
System.out.println ("sum is" + sum)
}
}
The running result is:
C: > java Sum
* * while statement * *
Sum is 55
* * do_while statement * *
Sum is 55
* * for statement * *
Sum is 55
You can compare these three kinds of loop statements, so as to select the appropriate statements in different situations.
Example 4.5 find all primes between 100 and 200
Public class PrimeNumber {
Public static void main (String args []) {
System.out.println ("* * prime numbers between 100 and 200 *")
Int nasty 0
Outer:for (int iTunes 101 / I < 200 * * iabilities / 2) {∥ outer loop
Int Kappa 15; ∥ select for convinence for (int juni2witj < = ksidjack +) {∥ inner loop
If (i%j==0)
Continue outer
}
System.out.print ("" + I)
∥ output a new line
If (n < 10) ∥ after 10 numbers
Continue
System.out.println ()
Nasty 0
}
System.out.println ()
}
}
The running result is:
C: > java PrimeNumber
* * prime numbers between 100,200 and 200 * *
101 103 107 109 113 127 131 137 139 149
151 157 163 167 173 179 181 191 193 197
one hundred and ninety nine
This example is implemented through a nested for statement. ! U4 §4.3 examples of outer rational sentences
The sentence outside the case includes try, catch, finally and throw. Compared with C, C + +, the sentence outside the case is
Peculiar to Java. We will give an introduction to the specialty in Chapter 8. ! U4 §4.4 explanatory sentences
Three kinds of annotated formulas can be adopted in Java:
1 ∥ is used for single-line comments. Comments start at ∥ and end at the end of the line.
2 / *... * / for multiline comments. Comments begin with / * and end with * /, and such comments cannot be nested within each other.
3 / *. * / is a doc comment unique to Java. It starts with / * and ends with * /. This kind of annotation is mainly
Used to support the JDK tool javadoc. Javadoc can recognize some special variables identified by the tag @ in comments, and set the
The doc annotation adds the HTML file it generates.
At this point, I believe you have a deeper understanding of "what are the flow control statements in JAVA?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.