for循环的注意事项
1 public static void main(String[] args) { 2 //注意: 1.在for循环中,三个 表达式都可以省略,但是分号必须编写,则出现死循环也叫做无限循坏,解决办法:按 3 /* for(;;){ 4 System . out . println ("OK") ; 5 }*/ 6 //注意: 2.在for循环中,省略表达式1,则出现编译错误,解决办法:将表达式1编写在for循环上面 7 /* int i = 1; 8 for(;i <= 5;i++) { 9 System. out .println(i) ; 10 } 11 */ 12 //注意: 3.在for循环中,省略表达式2,则出现死循环或无限循环,也就是说当省略表达式2时,则条件默认为true 13 /* for(int i = 1; ;i++) { 14 System. out.println(i) ; 15 }*/ 16 //注意: 4. 在for循环中,当省略表达式3,则出现死循环,解决办法:将表达式3编写在循环体中最后一条语句 17 /* for(int i = 1;i <= 5;){ 18 System . out. println (i) ; 19 i++; 20 }*/
while 循环练习题
使用while循环完成输出所有三位数中能被4整除的数,并且每行显示5个
1 public static void main(String[] args) { 2 //练习10:使用while循环完成输出所有三位数中能被4整除的数,并且每行显示5个 3 int i = 100; 4 int count = 0;//用来计算有几个能被4整除的数字 5 while (i<=999){ 6 if(i%4 == 0){ 7 System.out.print(i+"\t"); 8 count++; 9 if(count%5 == 0){ 10 System.out.println(); 11 } 12 13 } 14 i++; 15 } 17 System.out.println(count); 18 }