while及do-while循环结构

1.循环部分

①初始化部分(init_statement)

②循环条件部分(test_exp)

③迭代部分(alter_statement)

④循环体部分(body_statement)

 

2.while循环格式:

[初始化语句]

While(布尔值测试表达式){

     语句或语句块;

     [更改语句;]

}

即:①

While(②){

③}

题32:1到100以内偶数及偶数的和。

Class TestWhile{

Public.out.println(string[]args){

Int i=2;

Int sum=0;

While(i<=100){

If(i%2==0){system.out.println(i);

Sum+=i;}

i++}

}

System.out.println(sum);

} }

3.do-while格式

   ①

  Do{④

       ③}

  While(②);

题33:1-100之间的所有偶数。

Class TestDoWhile{

Public static void main(string[]args){

Int i=1;

Do{if(i%2==0){

System.out.println(i);}

i++;}

While(i<=100);

} }

 

4.①for循环和while循环一定可以相互转化。

②while循环与do......while循环区别:do...while循环至少会执行1次,也可以相互转换。

5.无限循环for( ; ; ){     }和while(true){       }

   注:无限循环内部要有一个终止循环的程序,使用break终止程序,否则就是死循环。

题34:①从键盘读入个数为10个的整数,并判断读入正数和负数的个数。

②从键盘读入个数不确定的整数,并判断读入正数和负数的个数,输入为0时结束程序。

(1)import.java.util.scanner;

Class TestForWhile1{

Public.static.println(string[]args){

Scanner s=new scanner(system.in);

Int a=0;

Int b=0;

For(i=0;i<10;i++){

System.out.println(“请输入第”+(i+1)+”个整数”);

Int num=s.nextInt();

If(num>0)

a++;

else if(num<0)

b++;

}

System.out.println(“正数的个数为”+a);

System.out.println(“正数的个数为”+b);

}

}

(2) import.java.util.scanner;

Class TestForWhile2{

Public static void main(string[]args){

Scanner s=new scanner(system.in);

Int a=0;

Int b=0;

For( ; ; ){

System.out.println(“请输入一个整数”);

Int num=s.nextInt();

If(num>0)

a++;

else if(num<0)

b++;

Else

break;}

System.out.println(“正数的个数为”+a);

System.out.println(“正数的个数为”+b);

} }

(3) import.java.util.scanner;

Class TestForWhile2{

Public static void main(string[]args){

Scanner s=new scanner(system.in);

Int a=0;

Int b=0;

While(true){

System.out.println(“请输入一个整数”);

Int num=s.nextInt();

If(num>0)

a++;

else if(num<0)

b++;

Else

break;}

System.out.println(“正数的个数为”+a);

System.out.println(“正数的个数为”+b);

} }

posted @ 2017-04-07 22:16  wanglele1988  阅读(2019)  评论(0编辑  收藏  举报