您的位置:首页 > 编程语言 > Java开发

Java基础知识02-流程控制-while

2017-12-23 18:51 375 查看
package cn.aparke.bbs.day03;

/**

* 循环结构:重复去执行的代码会使用到循环

*

* 1.while循环——————当型循环,指的是当满足某个条件的时候循环开始,直到循环的

* 条件为假了那么循环结束,如果一开始循环就为假则循环一次都不执行

* 语法:

* 表达式1;

* while(条件表达式2){

* 循环的语句表达式3;

* ….

*

* 改变循环变量的值表达式4;

* }

* while循环的四要素:

* 1.初始化循环变量 如 int count = 60,int i = 1; char word = ‘A’….

* 表示循环从什么时候 开始,一般情况下循环条件的赋值用 对应的整型或者字符、字符串类型

* 的表达式表示

* 2.确定循环的次数即循环条件,是一个boolean类型的值,可以是关系(比较)表达式

* 或者逻辑表达式、布尔类型的值等等

* 条件为真的时候循环开始执行,如果条件为假则循环结束

* 即其特点为先判断、后执行

* 3.循环操作的语句,可以有多条,放在循环体{}之中

* 4.每执行一次循环之后一定要改变循环变量的初始值,否则循环条件永远为真

* 循环就变成了死循环

*

* while循环的特点

* 1.while(){}该结构中循环体{}可以省略不写,但只能控制一条语句(复合语句)

* 建议大家不要轻易省略;

* 2.while()后面不要加上了分号,如 while();{}.如果是这样的话那么的

* while循环将会是死循环,并且对应的循环体{}和while之间没有任何联系了

* while();{}这种结构等同于

* while(){空的循环体}

* {

* 原本的循环语句

* }

* 两者彻底的分离了

* 3.先判断、后执行

* 4.条件一开始就为假则循环一次都不执行

*

*

*

*

*/

public class TestWhile1 {

public static void main(String[] args) {
int count = 60;
while (count>0)
{
System.out.println("打印第"+count+"个学生的简历");
count--;
}
System.out.println("count="+count);
}
}
class TestWhile2 {
//   1 1 2 3 5 8 13 21 ...
public static void main(String[] args) {
int i = 1;     //初始化循环变量 即第一要素
int num1 = 1;  //第一项
int num2 = 1;  //第二项
System.out.print(num1+" "+num2+" ");
while (i<19) //第二要素 循环条件
{
//循环的第三要素 循环语句
int num3 = num2+num1;
System.out.print(num3+" ");
//完成将num2的值交换给num1,然后再将num3的值交还给num2
num1 = num2;
num2 = num3;
//循环的第四要素 改变循环变量的值
i++;
}
}
}ss TestWhile3 {
//   1到100之间的奇数偶数
public static void main(String[] args) {

//第一要素
int i = 0;
int oddSum = 0;
//int evenSum = 0;
int count = 0;
while (i<101) //第二要素
{
//第三要素  奇数 偶数
if(i%2==0)
{
System.out.printf("%4d+%4d=%4d\t",i,oddSum,i+oddSum);
oddSum = oddSum + i;
count++;
if(count%5==0)
System.out.println();
}
//第四要素
i++;
}
}
}

class TestWhile4 {
//   6! = 6*5*4*3*2*1 = 720
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个整数:");
//第一要素
int num = sc.nextInt();
System.out.print(num+"!= ");
int result = 1; //记录乘积
while (num>=1) //第二要素
{
//第三要素
result*=num;
if(num==1)
System.out.print(num+" = ");
else
System.out.print(num+" * ");
//第四要素
num--;
}
System.out.println(result);
}
}


class TestWhile5 {
//   6! = 6*5*4*3*2*1 = 720
public static void main(String[] args) {
int i = 0;
while (i>5)
{
System.out.println("我爱你们!宝宝们!大家辛苦了哦!");

}
System.out.println("循环一次都没执行啊!");
}class TestWhile6 {

public static void main(String[] args) {
int year = 2012; // 记录年份
double students = 2.5; // 初始化循环变量
while (students < 10) {
students = students * 1.25;
year = year + 1;
System.out.println("下一年的人数" + students + "年份" + year);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 流程控制 结构