May 31, 2021 Article blog
This article was reproduced from the public number: Java Chinese community
Recently looking at
the
basics of
Java,
part of which is about looping, the syntax of loops is divided into three types:
for
while
do-while
as shown in the following illustration:
But I was surprised to find that I had never used
do-while
in my previous career (11 years), so I asked my little buddies in the group and found that it was rarely used.
Let's first look at the syntax of do-while:
do {
// statements
} while (expression);
Note: The last semicolon cannot be omitted, otherwise compilation errors will be prompted.
Its execution flow is shown in the following diagram:
So where exactly does it work?
After many searches and consulting sessions, I finally found two relatively satisfactory usage scenarios, and then came together to see.
For the ticket-snatching business, regardless of 3721, first rob again, and then judge whether the ticket-snatching success, if the successful ticket-snatching exit cycle, otherwise continue to carry out ticket-snatching, the implementation of the pseudo-code as follows:
do {
// 抢票代码...
} while (没抢到票);
Idea provider: Jia Wei
After extensive searching, it has been found that there are also a small number of scenes
do-while
in JDK's source code, such as
Integer
in-feed conversion, the relevant source code is as follows:
static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;
int mask = radix - 1;
do {
buf[offset + --charPos] = Integer.digits[val & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}
For example, decimal-to-binary will perform this method, in the business of progressive conversion, no matter what the case, will be executed at least once, so this business scenario is very suitable for
do-while
Confucius said: Warm and new. W
hen we have learned a lot of knowledge, look back on this knowledge, find it interesting, this is a great pleasure of knowledge.
In this article, we describe two
do-while
usage scenarios, ticket-snatching, and feed conversions, and what
do-while
scenarios do you know?
The above is
W3Cschool编程狮
about
do-while, Java easy to ignore the statement
of the relevant introduction, I hope to help you.