In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the "java loop sentence example usage", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's train of thought slowly in depth, together to study and learn "java loop sentence example usage" bar!
5.2.1 while statement
The while statement is the most basic loop statement of Java. When its control expression is true, the while statement repeats a statement or block of statements. Its general format is as follows:
While (condition) {
/ / body of loop
}
A conditional condition can be any Boolean expression. As long as the conditional expression is true, the loop body is executed. When the conditional condition is false, program control is passed to the statement line immediately following the loop. Curly braces are unnecessary if only a single statement needs to be repeated.
The following while loop subtracts the count from 10 and prints out 10 lines of "tick".
/ / Demonstrate the while loop.
Class While {
Public static void main (String args []) {
Int n = 10
While (n > 0) {
System.out.println ("tick" + n)
N-talk-
}
}
}
When you run this program, it will "tick" 10 times:
Tick 10
Tick 9
Tick 8
Tick 7
Tick 6
Tick 5
Tick 4
Tick 3
Tick 2
Tick 1
Because the while statement evaluates the conditional expression at the beginning of the loop, if the condition is false at the beginning, the loop body will not be executed once. For example, in the following program, a call to println () is never executed:
Int a = 10, b = 20
While (a > b)
System.out.println ("This will not be displayed")
The loop body of a while loop (or any other loop of Java) can be empty. This is because an empty statement (null statement) (a statement consisting of only one semicolon) is syntactically legal in Java. For example, the following program:
/ / The target of a loop can be empty.
Class NoBody {
Public static void main (String args []) {
Int i, j
I = 100
J = 200
/ / find midpoint between i and j
While (+ + I
< --j) ; // no body in this loop System.out.println("Midpoint is " + i); } } 该程序找出变量i和变量j的中间点。它产生的输出如下: Midpoint is 150 该程序中的while 循环是这样执行的。值i自增,而值j自减,然后比较这两个值。如果新的值i仍比新的值j小,则进行循环。如果i等于或大于j,则循环停止。在退出循环前, i 将保存原始i和j的中间值(当然,这个程序只有在开始时i比j小的情况下才执行)。正如你看到的,这里不需要循环体。所有的行为都出现在条件表达式自身内部。在专业化的Java 代码中,一些可以由控制表达式本身处理的短循环通常都没有循环体。 5.2.2 do-while 循环 如你刚才所见,如果while 循环一开始条件表达式就是假的,那么循环体就根本不被执行。然而,有时需要在开始时条件表达式即使是假的情况下,while 循环至少也要执行一次。换句话说,有时你需要在一次循环结束后再测试中止表达式,而不是在循环开始时。幸运的是,Java 就提供了这样的循环:do-while 循环。do-while 循环总是执行它的循环体至少一次,因为它的条件表达式在循环的结尾。它的通用格式如下: do { // body of loop } while (condition); do-while 循环总是先执行循环体,然后再计算条件表达式。如果表达式为真,则循环继续。否则,循环结束。对所有的Java 循环都一样,条件condition 必须是一个布尔表达式。下面是一个重写的"tick"程序,用来演示do-while 循环。它的输出与先前程序的输出相同。 // Demonstrate the do-while loop. class DoWhile { public static void main(String args[]) { int n = 10; do { System.out.println("tick " + n); n--; } while(n >0)
}
}
Although the loop in this program is technically correct, it can be written more efficiently as follows:
Do {
System.out.println ("tick" + n)
} while (--n > 0)
In this example, the expression "--n > 0" combines the decrement of n value with the test whether n is 0 or not in one expression. This is how it works. First, execute the-- n statement, decrement the variable n, and then return the new value of n. This value is compared to 0, and if it is greater than 0, the loop continues. Or it's over.
The do-while loop is especially useful when you make menu selections because you usually want the menu loop body to be executed at least once. The following program is a simple help system that implements Java selection and repetition statements:
/ / Using a do-while to process a menu selection
Class Menu {
Public static void main (String args [])
Throws java.io.IOException {
Char choice
Do {
System.out.println ("Help on:")
System.out.println ("1. If")
System.out.println ("2. Switch")
System.out.println ("3. While")
System.out.println ("4. Do-while")
System.out.println ("5. For")
System.out.println ("Choose one:")
Choice = (char) System.in.read ()
} while (choice
< '1' || choice >'5')
System.out.println ("")
Switch (choice) {
Case '1clients:
System.out.println ("The if:")
System.out.println ("if (condition) statement;")
System.out.println ("else statement;")
Break
Case '2clients:
System.out.println ("The switch:")
System.out.println ("switch (expression) {")
System.out.println ("case constant:")
System.out.println ("statement sequence")
System.out.println ("break;")
System.out.println ("/ /...")
System.out.println ("}")
Break
Case '3pm:
System.out.println ("The while:")
System.out.println ("while (condition) statement;")
Break
Case '4pm:
System.out.println ("The do-while:")
System.out.println ("do {")
System.out.println ("statement;")
System.out.println ("} while (condition);")
Break
Case '5clients:
System.out.println ("The for:")
System.out.print ("for (init; condition; iteration)")
System.out.println ("statement;")
Break
}
}
}
The following is a sample output of the program execution:
Help on:
1. If
2. Switch
3. While
4. Do-while
5. For
Choose one:
four
The do-while:
Do {
Statement
} while (condition)
In the program, the do-while loop is used to verify that the user has entered a valid selection. If not, the user is required to re-enter. Because the menu needs to be displayed at least once, the do-while loop is the appropriate statement to accomplish this task.
A few other points about this example: note that characters entered from the keyboard are read by calling System.in.read (). This is a Java console input function. Although Java's terminal Iamp O (input / output) method is discussed in detail in Chapter 12, System.in.read () is used here to read in the user's selections. It reads characters from standard input (returns integers, so defines the return value choice as character). By default, standard input enters the buffer by line, so you must press enter before any characters you enter can be sent to your program.
The terminal input function of Java is quite limited and difficult to use. Furthermore, most real Java programs and applets (applets) have a graphical interface and are window-based. As a result, there is not much input to the terminal in this book. However, it is useful in this example. Another point: because System.in.read () is used, the program must specify the throws java.io.IOException clause. This line of code is necessary to handle input errors. This is part of Java's exception handling and will be discussed in Chapter 10.
5.2.3 for cycle
A simple format of a for loop was used in Chapter 2. As you will see, the for loop is a powerful and flexible structure. The following is a common format for for loops:
For (initialization; condition; iteration) {
/ / body
}
If only one statement needs to be repeated, curly braces are not necessary.
The execution of the for loop is as follows. The first step is to execute the initialization part of the loop when it starts. Typically, this is an expression that sets the value of the loop control variable as a counter to control the loop. It is important for you to understand that initialization expressions are executed only once. Next, calculate the value of the condition condition. The conditional condition must be a Boolean expression. It usually compares the loop control variable with the target value. If the expression is true, the loop body is executed; if false, the loop terminates. The next step is to execute the iterative part of the loop body. This part is usually an expression that adds or decreases loop control variables. Next, repeat the loop, first evaluate the value of the conditional expression, then execute the loop body, and then execute the iterative expression. This process is repeated until the control expression becomes false.
Here is the "tick" program that uses the for loop:
/ / Demonstrate the for loop.
Class ForTick {
Public static void main (String args []) {
Int n
For (n-10; n > 0; n-m -)
System.out.println ("tick" + n)
}
}
Declare loop control variables in a for loop
The variables that control the for loop are often used only for that loop, not elsewhere in the program. In this case, you can declare the variable in the initialization part of the loop. For example, the following rewrites the previous program so that the variable n is declared as an integer in the for loop:
/ / Declare a loop control variable inside the for.
Class ForTick {
Public static void main (String args []) {
/ / here, n is declared inside of the for loop
For (int nasty 10; n > 0; nmuri -)
System.out.println ("tick" + n)
}
}
When you declare a variable within a for loop, it is important to keep in mind that the variable's scope ends after the for statement is executed (therefore, the variable's scope is limited to the for loop). Outside the for loop, the variable does not exist. If you need to use a loop control variable elsewhere in the program, you cannot declare it in the for loop.
Since the loop control variable is not used elsewhere in the program, most programmers declare it in the for loop. For example, the following is a simple program for testing primes. Note that since I is not needed elsewhere, the loop control variable I is declared in the for loop.
/ / Test for primes.
Class FindPrime {
Public static void main (String args []) {
Int num
Boolean isPrime = true
Num = 14
For (int iTunes 2; I
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.