美文网首页
while循环和条件分支

while循环和条件分支

作者: HanMeng | 来源:发表于2018-02-04 17:08 被阅读0次

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

相关文章

  • while循环和条件分支

    while循环 while循环的范例: public class Loopy{ public static vo...

  • 前端11

    条件判断:if...else条件分支:switch...case循环:for while do...while...

  • if语句练习

    条件判断:if...else条件分支:switch...case循环:for while do...while 数...

  • Shell 逻辑控制

    逻辑控制 条件 if 分支 case、select 循环 for、while、until break 和 cont...

  • 学习小甲鱼教程

    反斜杠的作用 \\ \n和r的区别 改进小游戏 条件分支 比较符号 循环 while while not tem...

  • Python_流程控制语句

    条件控制、循环控制、分支 if else、for while、switch 注释:单行注释 # (ctrl + /...

  • 流程控制

    1、条件语句 1.1 if条件语句 1.2 switch多分支语句 2、循环语句 2.1 while循环语句 2....

  • 巧用do{...}while(0)

    在学习第一门编程语言时,就已经介绍了顺序分支、条件分支、循环分支。比如循环分支有for、while、do-whil...

  • while和do while循环语句

    while 循环和 do…while 循环的相同处是:都是循环结构,使用 while(循环条件) 表示循环条件,使...

  • 重拾Java (三)流程控制语句

    重拾Java第三篇,流程控制语句,基础喔 分支结构 选择结构 循环结构 while循环,while(判断条件),当...

网友评论

      本文标题:while循环和条件分支

      本文链接:https://www.haomeiwen.com/subject/zvvmzxtx.html