1.循环部分java
①初始化部分(init_statement)测试
②循环条件部分(test_exp)string
③迭代部分(alter_statement)it
④循环体部分(body_statement)for循环
2.while循环格式:test
[初始化语句]import
While(布尔值测试表达式){循环
语句或语句块;程序
[更改语句;]im
}
即:①
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);
} }