当前位置: 首页 > news >正文

Java中的while和do...while循环

while和do...while循环

  • while循环
    • 基本语法
    • 执行流程
    • 注意事项
    • 练习
  • do...while循环
    • 基本语法
    • 说明
    • 流程图
    • 练习

while循环

基本语法

循环变量初始化;
while(循环条件){循环体(语句);循环变量迭代;
}

1)while循环也有四要素:循环变量初始化,循环条件,循环体(语句),循环变量迭代。
2)只是四要素放的位置和for不一样。

执行流程

在这里插入图片描述

注意事项

1)循环条件是返回一个布尔值的表达式(只能为真或假)
2)while循环是先判断再执行语句

练习

用while循环打印1-100之间所有能被3整除的数

public class Test{public static void main(String[] args){int i = 1;while(i <= 100){if(i % 3 == 0){System.out.println(i + "能被3整除");}i++;}}
}

随时改变范围值和被n整除的数

import java.util.Scanner;
public class ForTest{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入初始范围:");int start = sc.nextInt();System.out.println("请输入结束范围:");int end = sc.nextInt();System.out.println("请输入需要被整除的整数:");int temp = sc.nextInt();int i = start;while(i <= end){if(i % temp == 0){System.out.println(i + "能被" + temp + "整除");}i++;}}
}

do…while循环

基本语法

do{循环体(语句);循环变量迭代;
}while(循环条件)**;**

说明

1.do while 是关键字,也有循环四要素,只是位置不一样
2.先执行再判断,一定至少执行一次
3.最后有一个 分号
4.while 和 do…while区别举例:我去要账,while循环先问对方还不还钱,对方说还钱,我直接就走了退出while循环,说不还,就揍他一顿;而do…while循环,见到对方先打一顿然后再问还不还钱,对方说还钱,我直接就走了退出循环,说不还,就再揍他一顿。

流程图

在这里插入图片描述

练习

1.用do…while循环统计1-200之间能被5整除但不能被3整除的个数

public class ForTest{public static void main(String[] args){int i = 1;int count = 0;do{if(i % 5 == 0 && i % 3 != 0){count++;}i++;}while(i <= 200);System.out.println("count = " + count);}
}

2.如果李三不还钱,则一直使出五连鞭,直到李三说还钱为止。(字符串比较用equals()方法)

import java.util.Scanner;
public class ForTest{public static void main(String[] args){Scanner sc = new Scanner(System.in);char answer = ' ';do{System.out.println("用五连鞭抽李三");System.out.println("问:还钱吗,回答y/n");answer = sc.next().charAt(0);}while(answer != 'y');}
}

http://www.mrgr.cn/news/42796.html

相关文章:

  • 代码随想录:冗余连接|、||
  • vim 操作
  • Yocto - 使用Yocto开发嵌入式Linux系统_07 构建使用的临时文件夹
  • 第 33 章 Ajax
  • 温度转换-C语言
  • 前端媒体查询的用法及案例
  • 746. 使用最小花费爬楼梯
  • 算法(食物链)
  • 算法(最大异或对)
  • 简单的a+b-C语言
  • 前端的混合全栈之路Meteor篇(三):发布订阅示例代码及如何将Meteor的响应数据映射到vue3的reactive系统
  • 深入浅出 CSS 定位:全面解析与实战指南
  • 三维世界的魅力:探索开源的Three.js案例
  • 【Linux】进程地址空间(初步了解)
  • 物理学基础精解【51】
  • SpringBoot基础(三):Logback日志
  • 【AIGC】2022-NIPS-视频扩散模型
  • 20241004给荣品RD-RK3588-AHD开发板刷Rockchip原厂的Android12时永不休眠的步骤
  • 国外电商系统开发-运维系统批量添加服务器
  • 论文笔记:Online Class-Incremental Continual Learning with Adversarial Shapley Value