Java基础之While循环

首先我们先假想需要打印一行字符串"hello gzitcast",打印100次

那么我们最笨的办法就是将该语句打印100遍System.out.println("hellogzitcast");

那么如何解决这种问题呢?

Java提供个一个称之为循环的结构,用来控制一个操作的重复执行。

public static void main(String[] args) {

       int count = 0;

       while (count < 100) {

           System.out.println("helloWord");

           count++;

}

System.out.println("over");


变量count初始化值为0,循环检查count<100 是否为true,如果为true执行循环体(while后{}之间的语句),输出"hello Word"语句,然后count自增一,重复循环,直到count是100时,也就是count<100为false时,循环停止。执行循环之后的下一条语句。

Java提供了三种类型的循环语句:while循环,do-while循环和for循环。

while语句格式

    while(条件表达式)

    {

    执行语句;

}

例: 想要打印5次hello world

publicstaticvoid main(String[] args) {

   System.out.println("hello world");

       System.out.println("hello world");

       System.out.println("hello world");

       System.out.println("hello world");

       System.out.println("hello world");

}

2、

publicstaticvoid main(String[] args) {

       int x = 0;

       while (x < 5) {

           System.out.println("hello java ");

       }

}

如果是在dos里编译和运行,是不会停止,除非系统死机。需要ctrl+c来结束。

这就是真循环或者死循环。因为x<5 永远为真。

publicstaticvoid main(String[] args) {

       int x = 0;

       while (x < 5) {

           System.out.println("hello java ");

           x++;

       }

    }

让x自增,那么就会有不满足条件的时候。循环就会结束。

练习:想要打印出1-100之间的奇数

publicstaticvoid main(String[] args) {

       int x = 1;

       while (x < 100) {

           System.out.println(x);

           x = x + 2;

       }

    }


public static void main(String[] args){

       int x=1;

       while(x<100){

          

           if(x%2!=0){

              System.out.print(x);

           }

           x++;

       }

       System.out.println();     

    }

例2:计算1+2+3+4+5+6+7+8+9 的值

int sum = 0;

       int i = 1;

       while (i < 10) {

           sum = sum + i;

           i++;

       }

       System.out.println(sum);


注意:要精确控制循环的次数。常犯错误是是循环多执行一次或者少执行一次。

例如会执行101次,想要执行100次,要么是count初始值为1,然后count<=100

要么是count初始值为0,coung<100

int count = 0;

       while (count <=100) {

           System.out.println("hello gzitcast");

           count++;

       }

       System.out.println("over");






  • 16
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值