while循环和条件分支

while循环

while循环的范例:

public class Loopy{

    public static void main(String[] args){

        int x=1;

        System.out.println("Before the Loop");

        while(x<4){

            System.out.println("In the loop");

            System.out.println("Value of x is"+x);

            x=x+1;

        }

        System.out.println("This is after the loop");

    }

}

输出:

Before the Loop

In the loop

Value of x is 1

In the loop

Value of x is 2

In the loop

Value of x is 3

This is after the loop



条件分支

在Java中if与while循环都是boolean测试,但语义从“只要不下雨就持续。。。”改成“如果不下雨就。。。”

class IfTest{

    public static void main(String[] args){

        int x=3;

        if(x==3){

            System.out.println("x must be 3");

        }

        System.out.println("This runs no matter what");

    }

}

输出:

x must be 3

This runs no matter what


上面的程序只会在x等于3这个条件为真的时候才会列出“x must be 3”。而第二行无论如何都会列出。

我们可以将程序加上else条件,因此可以指定“如果下雨就撑雨伞,不然的话就戴墨镜”

class IfTest2{

    public static void main(String[] args){

        int x=2;

        if(x==3){

            System.out.println("x must be 3");

        }

        else{

            System.out.println("x is NOT 3");

        }

        System.out.println("This runs no matter what");

    }

}

输出:

x is NOT 3

This runs no matter what

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容