循环结构 :while
2024-09-07 10:06:10
循环结构 :while
循环四要素:
1.初始化条件
2.循环条件
3.循环体
4.迭代条件
格式:
1.初始化条件
while(2.循环条件){
3.循环体
4.迭代条件
}
public class WhileTest{ public static void main(String[] args){ //需求 :求100以内的偶数,偶数的个数,偶数的总和
int count = 0; //偶数的个数
int sum = 0; //偶数的总和
int i = 1;//初始化条件
while(i <= 100){//循环条件
//循环体
if(i % 2 == 0){
count++;
sum += i;
System.out.println(i);
}
//迭代条件
i++;
} System.out.println("count=" + count + " sum=" + sum); }
}
/* 从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。 */
import java.util.Scanner;
public class NumberCountTest{ public static void main(String[] args){ Scanner sc = new Scanner(System.in);
int positiveNumber = 0; //正数
int negativeNumber = 0; //负数 while(true){
//读取数据
int number = sc.nextInt();
//判断
if(number > 0){//正数
positiveNumber++;
}else if(number < 0){//负数
negativeNumber++;
}else{//退出循环
break;
}
} System.out.println("正数的个数" + positiveNumber + " 负数的个数" + negativeNumber);
}
}
最新文章
- 提交本地项目到github服务器
- 【Swift学习】Swift编程之旅---Subscripts下标(十六)
- css font-weight原理
- iOS 键盘隐藏
- bzoj 4031: [HEOI2015]小Z的房间 轮廓线dp
- Hibernate 的HQL语句,初级
- WINDOWS BITLOCK
- mac复制粘贴剪切
- 2017/4/27-Gradle的配置与Spring的下载
- 【BBED】BBED模拟并修复ORA-08102错误
- 记录在vue中使用jsx时踩过的坑
- 学习ELk之----02. Elastic Search操作入门
- springboot配置SSL自签名证书
- 文件系统的描述信息-/etc/fstab
- [转帖]NUMA架构的CPU -- 你真的用好了么?
- elasticsearch 单机多实例
- 6-7 树的层次遍历 uva122
- android根据图片路径显示图片
- INSTALL_FAILED_INVALID_APK
- LAMP结合discuz论坛的配置