三大循环
用IDEA学习Java的第四天(三大循环)
循环结构
while循环
while(布尔表达式){
//循环内容
}
用while循环输出1~100
package com.zjl.struct;
public class WhileDemo01 {
public static void main(String[] args) {
int i=0;
while (i<100){
i++;
System.out.println(i);
}
}
}
输出100以内所有数之和
package com.zjl.struct;
public class WhileDemo02 {
public static void main(String[] args) {
int i=0;
int sum=0;
while(i<100){
i++;
sum+=i;
}
System.out.println(sum);
}
}
do ...while循环
-
对于while语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。
-
do...while循环和while循环相似,不同的是,do...while循环至少会执行一次。
do{
//代码语句
}while();
while循环和do...while循环的区别
- while先判断后执行。do...while是先执行后判断
- Do...while总是保证循环体会被至少执行一次!
package com.zjl.struct;
public class DoWhileDemo {
public static void main(String[] args) {
int a=0;
while(a<0){
System.out.println(a);
}
System.out.println("****************");
do {
System.out.println(a);
}while (a<0);
}
}
for循环
- for循环使一些循环结构变得更加简单
- for循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构。
- for循环执行的次数是在执行前就确定的。
for(初始化;布尔表达式;更新){
//代码语句
}
死循环
package com.zjl.struct;
public class ForDemo06 {
//死循环
/*
关于for循环有以下几点说明
最先执行初始化步骤,可以声明一种类型,但可初始化成一个或多个循环控制变量,也可以是空语句。
然后检查布尔表达式的值。如果为true,循环体被执行,如果为false,循环终止,并开始执行循环体后面的语句。
执行一次循环之后,更新循环控制变量(迭代因子控制循环变量的增减),
再次检查布尔表达式,循环执行上面的过程。
*/
public static void main(String[] args) {
for(;;){
System.out.println("A");
}
}
}
运用for循环打印三角形
package com.zjl.struct;
public class ForDemo05 {
public static void main(String[] args) {
//打印三角形
for (int i = 1; i <=5; i++) {
for(int k=5;k>i;k--){
System.out.print(" ");
}
for (int j=1;j<=2*i-1;j++){
System.out.print("*");
}
System.out.println("");
}
}
}
用while或for循环输出1~1000能被5整除的数,并且每行输出三个
package com.zjl.struct;
public class ForDemo02 {
public static void main(String[] args) {
//用while或for循环输出1~1000能被5整除的数,并且每行输出三个
for (int i = 1; i <=1000; i++) {
if(i%5==0){
System.out.print(i+" ");
}
if(i%(5*3)==0){
//System.out.println();
System.out.println("\n");
}
}
}
}
增强for循环
主要用于数组和集合的增强型for循环
for(声明语句:表达式){
//代码句子
}
- 声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
- 表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
break
break在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句。(break语句也在switch语句中使用)
package com.zjl.struct;
public class BreakDemo {
public static void main(String[] args) {
int i=0;
while (i<100){
i++;
System.out.println(i);
if(i==30){
System.out.println("end");
break;
}
}
}
}
Continue
continue语句在循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。
package com.zjl.struct;
public class ContinueDemo {
public static void main(String[] args) {
int i=0;
while (i<100){
i++;
if(i%10==0) {
System.out.println();
continue;
}
System.out.print(i+" ");
}
}
}

浙公网安备 33010602011771号