其他分享
首页 > 其他分享> > 032- for循环语句

032- for循环语句

作者:互联网

问题
请在控制台里面打印10次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("helloworld");

好吧,如果要打印10000次呢?累不死你才怪。
这时就需要使用for循环语句来帮我们解决了。

 

语法

for(初始化表达式;条件表达式;循环后的操作表达式) {
    循环体;
}

例子:

public class json
{
    public static void main(String[]args){

        //初始化i的值为0;只要i<10则循环一次打印语句,每循环一次,i自增1.
        for(int i =0;i<10;i++){
        
            System.out.println("hello world");
        }

    }
}

 

执行过程:

1.执行初始化语句,并且在整个循环过程里面只执行一次

2.执行判断条件语句,看其返回值是true还是false

* 如果是true,就继续执行
* 如果是false,就结束循环,整个流程结束

3.执行循环体语句

4.执行循环后的操作表达式

5.程序回到步骤2继续。

 

for循环中的变量

在for循环中定义的变量只能在循环内部访问和使用,循环外是无法访问和使用的。

for(int i=0;i<10;i++){
        System.out.println("Hello");
}
//报错,在循环外无法访问和使用i
System.out.println(i);

因此下面代码是可以正常执行的:

 

死循环

倘若for循环里面的循环体只有一行代码,则大括号可以省略,但是不建议省略,最好写上。
如果for循环编写不当,可能会造成死循环,程序永远不会停止,在编写程序时一定要避免,下面就是一个死循环。

public class json
{
    public static void main(String[]args){

        for(;;){
            
            System.out.println("test");
        }

    }
}

嵌套for循环

for循环语句还可以嵌套使用

public class json
{
    public static void main(String[]args){

        for(int i=5;i>0;i--){
    //因为该for循环是在上面for循环的内部,所以是可以访问变量i的
        for(int j=0;j<i;j++){
        System.out.print(j+" ");
     }

    //换行
        System.out.println();

    }

    }
}

 

运行结果:

 

 

1.计算1-100所有的奇数求和

1.在for循环里面加上if语句来判断当前循环的数字是否为奇数

public class json
{
    public static void main(String[]args){

    int sum = 0;
    for (int i =1; i<=900;i++ )
    {
        if(i%2!=0){
        
        //奇数
        //追加
        sum+=i;

        }
    }
    
    System.out.println(sum);

    

    }
}

 

标签:语句,System,helloworld,println,循环,032,public,out
来源: https://www.cnblogs.com/Chamberlain/p/11396202.html