Java program flow control example tutorial
Java Program Flow Control
This article separately organizes the knowledge points of loop structures:
As mentioned before, loop structures are divided into: for loop, while loop, do...while Loops are the three most basic loop structures; versions after JDK 1.5 also provide a foreach loop for traversing arrays and collections.
The four components of the loop statement:
Initialization part
Loop condition part
Loop body part
Iteration part
for loop:
for (initialization condition; loop condition; iteration part){
Loop body
}
1 public class TestFor {2 public static void main(String[] args) {3 //基础for循环,讲一个语句打印多次4 for(int i=0; i<7; i++){5 System.out.println("Hello World!! 第"+i+"次打印");6 }7 }8 }
Exercise: Print 1-100 All even numbers
1 public class TestFor { 2 public void PrintNum(){ 3 for(int i=1; i<=100; i++){ 4 if(i%2==0){//对2取余,若为0则证明是偶数,执行打印语句,反之则继续循环直到满足偶数条件或者i>0 5 System.out.println("i="+i); 6 } 7 } 8 } 9 public static void main(String[] args) {10 TestFor testFor = new TestFor();11 testFor.PrintNum();12 }13 }
Exercise: Write code to loop from 1 to 150 and print a value in each line. In addition, you need to print "foo" in each line that is a multiple of 3, in Print "biz" on every line that is a multiple of 5,
Print "baz" on every line that is a multiple of 7
1 public class TestFor { 2 public void FooBizBaz(){ 3 for(int i=1; i<=150; i++){ 4 System.out.print(i+":"); 5 if(i%3 == 0){ 6 System.out.print(" foo"); 7 } 8 if(i%5 == 0){ 9 System.out.print(" biz");10 }11 if(i%7 == 0){12 System.out.print(" baz");13 }14 System.out.println();15 }16 }17 public static void main(String[] args) {18 TestFor testFor = new TestFor();19 testFor.FooBizBaz();20 }21 }
Note: Must It should be noted that else if(){} cannot be used in this question. Once used, it will be impossible to print three fields at the same time in the number of lines that meet the multiples of 3, 5, and 7 at the same time, because once one of them meets the judgment condition, it will not Execute the if judgment statement below to directly jump out of the current loop and execute the next loop.
There are also many small basic for loop algorithms, such as printing the sum of all odd numbers from 1 to 100, printing out all the narcissus numbers (you can search for the daffodil numbers yourself), these questions can Practicing on your own will help strengthen your understanding of the for loop, so I won’t go into details here.
while loop:
Initialization condition
while (loop condition){
Loop body
Iteration condition
}
Example: Output all even numbers within 1-100
1 public class TestWhile { 2 public void evenNum(){ 3 int i = 1; //初始化条件 4 while(i<=100 ){//循环条件 5 6 if(i % 2 == 0){ 7 System.out.println("i="+i); 8 }//循环体 9 10 i++;//迭代条件11 }12 }13 14 public static void main(String[] args) {15 TestWhile testWhile = new TestWhile();16 testWhile.evenNum();17 }18 }
Note: The for loop and the while loop can be transformed into each other, because they have the same four parts, but the four parts are placed in different positions.
Another looping method of while loop:
do...while loop:
Initialization conditions
##do{
Loop body
Iteration condition
}while( Loop condition);
It can be seen from the above structure that the do...while loop first performs a loop to determine whether the loop condition is satisfied. If it is satisfied, Proceed to the next cycle, and stop the cycle if it is not satisfied.
Example: Print all even numbers from 1-100
1 public class TestDoWhile { 2 public void evenNum(){ 3 int i = 1; 4 do{ 5 if(i % 2 == 0){ 6 System.out.println("i="+i); 7 } 8 i++; 9 }while(i <= 100);10 }11 public static void main(String[] args) {12 TestDoWhile testDoWhile = new TestDoWhile();13 testDoWhile.evenNum();14 }15 }
do...while和while循环的区别:
do...while循环中 初始化条件即使不满足循环条件也会直接执行一次循环体再进行循环条件判断,所以循环体至少被执行一次,而while循环是必须满足循环条件才会执行循环体。
嵌套循环
顾名思义,嵌套循环就是再一个循环中还能再声明一个循环
几种嵌套方式:
1.for循环中能够嵌套一个for或多个for;
2.while循环中可以嵌套一个或多个while循环;
3.for循环中可以嵌套一个或多个while循环;
4.while循环中可以嵌套一个或多个for循环;
5.for循环中可以嵌套一个或多个for/while循环;
6.while循环中可以嵌套一个或多个for/while循环。
示例:
For之间嵌套
1 public class TestForFor { 2 /*打印出 ***** 3 * ***** 4 * ***** 5 * ***** 6 * */ 7 public void forQianTao(){ 8 for(int i = 1; i <= 4;i++){ 9 for(int j = 1; j<=5 ;j++){10 System.out.print("*");11 }12 System.out.println();13 }//此为两层循环,i用于控制打印的行数,j用于控制打印的列数14 }15 public static void main(String[] args) {16 TestForFor testForFor = new TestForFor();17 testForFor.forQianTao();18 }19 20 }
其它几种嵌套循环可以参考上面的示例,结构类似。自己可以进行练习,如通过嵌套循环打印九九乘法表、或者打印一个由星号组成的菱形图案,每个星号之间要有一个空格,这些题可以加强对嵌套循环的理解。
The above is the detailed content of Java program flow control example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
