循环结构语句
循环语句可以在满足循环条件下,反复执行某一段代码,这段被重复执行的代码被称为循环体语句,当反复执行这个循环体时,需要在合适的时候把循环判断条件修改为false,从而结束循环,否则循环将一直执行下去,形成死循环。
循环四要素:
- 循环初始化:一条或多条语句,这些语句完成一些初始化操作,让循环开始执行
- 循环继续条件:控制循环是否继续或结束的条件
- 循环体:需要被循环执行的代码
- 循环步长(间距,周期):当前循环和下一次循环之间的差量
for循环语句
一般用于次数已知的情况下
for循环语句格式:
for(初始化语句;继续条件;步长){
循环体;
}
执行流程:
- 执行初始化语句
- 执行继续条件判断
如果是true,继续执行
如果是false,循环结束 - 执行循环体语句
- 执行步长
- 回到2继续
案例:
class Demo{
public static void main (String[] args){
int sum = 0; //声明变量,用于保存各数相加的结果
for(int i = 0 ; i <= 50 ; i+=2){ //指定循环条件及循环体
sum = sum+i;
}
System.out.println("2到50之间所有偶数之和为:"+sum);
}
}
注意事项:
-
循环继续条件语句的结果是一个boolean类型
-
循环体语句如果是一条语句,大括号可以省略
-
有大括号就没有分号,有分号就没有大括号
-
有时会使用for循环的特殊语法格式来实现死循环
for( ; ; ){ } //通过break语句跳出循环,如: for( ; ; ){ if(x <10) break; x++; }
-
for循环中的初始动作可以是0个或是多个以逗号隔开的变量声明语句或赋值表达式,例如:
for (int i = 0,j = 0 ; i + j < 10 ; i++ , j++){ } //for循环中每次迭代后的动作可以是0个或多个以逗号隔开的语句。例如: for( int i = 1 ; i <100 ; System.out.println(i),j++);
-
如果省略for循环中的循环继续条件,则隐含地认为循环继续条件为ture。因此下面图a中给出的语句和图b中给出的语句一样,它们都是无限循环。但是,为了避免混肴,最好还是使用图c中的等价循环:
foreach循环语句
foreach语句是for语句的特殊简化版本,不能完全取代for语句,但任何foreach语句都可以改写成for语句。foreach并不是关键字,习惯上将这种特殊的for语句格式称为foreach语句。foreach语句在遍历数组等方面提供了很大的方便。
语法格式:
for(元素变量 x : 遍历对象 obj){
引用了x的Java语句;
}
foreach语句中的变量x,不必对其进行初始化。
案例:
class Demo{
public static void main(String[] args){
int[] arr = {5,4,9,7,1};
System.out.println("一维数组中的元素分别是:");
for(int x : arr){ //foreach语句, int x 引用的变量,arr指定要循环遍历的数组,最后将x输出
System.out.println(x);
}
}
}
习题:
1.
class Class25{
public static void main(String[] args){
System.out.println(sumDifits(234));
}
public static long sumDifits(long n){ //120
long a = 0 ;
long temp = 0;
for( long b = n ; b != 0; b=b/10){
temp = a;
a = b%10;
a=a+temp;
}
return a;
}
}
package com.openlab.day04;
public class Home15_4 {
public static void main(String[] args) {
for(int i = 1 ; i <= 6 ; i++) {
for(int k = 1 ; k < i ; k++) {
System.out.print(" ");
}
for(int j = 1 ; j <= 7-i ; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
package com.openlab.day05;
class Home16{
public static void main(String[] args){
/*
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
*/
for(int i=1;i<=8;i++){
for(int k=1;k<=8-i;k++){
System.out.print(" ");
}
for(int j=-(i-1);j<=i-1;j++){
System.out.printf("%-4.0f",Math.pow(2,i-1-Math.abs(j)));
}
System.out.println();
}
}
}