packagecom.zedhz.scanner;importjava.util.Scanner;publicclassDemo04{publicstaticvoidmain(String[] args){//输入多个数字,并求和与平均数,每输入一个数字以回车确认,通过输入非数字来结束程序,并输出执行结果Scanner scanner =newScanner(System.in);//和double sum =0;//计算输入了多少个数字int m =0;//通过循环判断是否还有输入,并对每一次进行求和,统计while(scanner.hasNextDouble()){double x = scanner.nextDouble();
m = m+1;//m++
sum = sum +x;}System.out.println(m +"个数的和为:"+ sum);System.out.println(m +"个数的平均数为:"+(sum / m));
scanner.close();}}
packagecom.zedhz.struct;publicclassWhileDemo07{publicstaticvoidmain(String[] args){int i =0;int sum =0;while(i<=100){
sum = sum + i;
i++;}System.out.println(sum);}}
do while
do…while循环在不满足条件的情况下至少会执行一次
While和do…while的区别
while先判断后执行,do…while是先执行后判断
do…while总是会保证循环体至少会被执行一次
packagecom.zedhz.struct;publicclassDowhileDemo09{publicstaticvoidmain(String[] args){int i =0;while(i<0){System.out.println(i);
i++;}System.out.println("=============");do{System.out.println(i);
i++;}while(i<0);}}
For循环
For循环是支持迭代的一种通用结果,是最有效最灵活的循环结构
For循环的执行次数是在执行前就确定的
packagecom.zedhz.struct;publicclassForDemo12{publicstaticvoidmain(String[] args){/**
* For循环实现1000以内能被5整除的数,每行显示3个
*/for(int i =0; i <=1000; i++){if(i%5==0){System.out.print(i+"\t");}if(i%(5*3)==0){System.out.println();}}/**
* While循环实现1000以内能被5整除的数,每行显示3个
*/int i =0;while(i<=1000){if(i%5==0){System.out.print(i+"\t");}if(i%(5*3)==0){System.out.println();}
i++;}}}