java语法-循环结构

循环结构

java中的循环结构有三大类:
for循环、while循环和do-while循环
for循环:确定循环次数。先判断,再循环。常用嵌套。

格式

for(参数初始化 ;循环的条件 ;循环变量的叠加  ){

  循环操作;

}

理解图:
在这里插入图片描述
案例:

public static void main(String[] args) {
//原始写法
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("HelloWorld");
System.out.println("-------------------------");


//用循环改进
for(int x=1; x<=10; x++) {
System.out.println("HelloWorld");
	}
}

do-while循环:不确定循环次数,但至少要循环一次。先循环,在判断。最后的分号不可省。

理解图:
在这里插入图片描述
格式

   do{

   循环操作

  } while(循环条件);

案例:

public static void main(String[] args) {
	int x=1;
	do {
	System.out.println("HelloWorld");
	x++;
	}while(x<=10);
}

while循环:不知道循环次数。先判断,再循环。常用死循环。用死循环时就要判断什么时候手动让他停止,而这个时候就常会定义一个Boolean类型的变量,让他初始值为true,到循环该结束时,让他的值为false。

理解图:

在这里插入图片描述
格式

 while(循环条件){

    循环操作;

  }

案例

public static void main(String[] args) {
	//输出10次你好帅

	//while循环实现
	int x=1;
	while(x<=10) {
	System.out.println("你好帅");
	x++;
	}
}

foreach循环语句是针对数组或集合进行元素迭代的一种通用结构。
foreach循环在第一次反复之前要进行变量声明及初始化。随后,它会测试数组或集合中是否还有可取元素,如果有将下一个可取元素取出存入到已声明变量中,逐次步进循环,直到数组或集合内部所有数据取完为止。

格式;

扫描二维码关注公众号,回复: 11249193 查看本文章
 for (声明变量 : 数组或集合对象) {
     循环体;
 }

理解图
在这里插入图片描述

在循环中常会用到的还有三种跳出循环的语句:

break:结束本次循环,继续执行循环后面的语句。跳到外层循环。

continue:跳过本次循环,剩余的语句继续,继续执行下一次。
注意:用在while循环里容易出现死循环。要将更新变量语句i++放在continue上面。

return:直接结束当前main方法,遇到return后,方法中的所有代码将不再执行。
注意:程序中要减少return的使用频率。一旦使用return,整个main方法结束。

猜你喜欢

转载自blog.csdn.net/qq_43402310/article/details/104185674