循環語句——for語句


一、for語句結構:
for (初始化表達式; 循環條件表達式 ;循環后的操作表達式 )
  {
    執行語句;
  }

 循環條件表達式,必須是true或false

 

示例:

class ForDemo
{
    public static void main(String[] args)
    {
        for (int x=0;x<3 ;x++ )
        {
            System.out.println("第"+x+"次"+"你好");
        }

    }
}

輸出結果:

第0次你好
第1次你好
第2次你好

 

執行順序圖解:

第1步 執行“初始化表達式”int x=0;

第2步 是否x<3

第3步 條件滿足(真),執行打印輸出語句

第4步 x++,結果為1

第5步 是否x<3

第6步 條件滿足(真),執行打印輸出語句

...

第10步 x++,結果為3

第11步 是否x<3,為假,停止

 

第一步是執行初始化表達式。第后只在循環表達式、執行語句、循環后的操作表達式三者之間循環。

 

二、for語句特點:

根據以上執行順序,得出以下結論:

符合條件時,初始化表達式只執行一次
只有條件表不滿足循環就停止。

 

 

三、變量的作用域(即作用范圍)

for(){}循環,變量初始值定義在for語句內部,執行完畢后,變量釋放。

如下,最后一句無法輸出,報錯:

class ForDemo
{
    public static void main(String[] args)
    {
        for (int x=0;x<3 ;x++ )
        {
            System.out.println("第"+x+"次"+"你好");
        }
        System.out.println(x);    //報錯。
    }
}    

 

while(){}循環,變量初始值定義在while語句外部,執行完畢后,變量仍存在。

如下,最后一句輸出3。因為在內存中,變量y仍存,同是值已經變為3。

class ForDemo
{
    public static void main(String[] args)
    {
        int y=0;
        while(y<3)
        {
            System.out.println("第"+y+"次"+"你好");
            y++;
        }
        System.out.println(y);        //輸出3
    }
}

 

總結:

for和while語句可以互換

變量只為循環增量存在,建議用for語句。

循環結速后,仍要使用變量進行其它運算,要用while語句。

 

四、特殊示例

1、初始化及循環后的語句,只要是一個正確的表達式,就可以(int i=0,不單單局限於這種格式)。變量的初始值可以定義在for循環外面。

class ForDemo
{
    public static void main(String[] args)
    {
        int x=1;
        for (System.out.println("a");x<3; System.out.println("c") )
        {
            System.out.println("d");
            x++;
        }
        System.out.println(x);    //3
    }
}    

 

輸出:

a
d
c
d
c
3

 

2、有多個表達式,用逗號“,”分隔

class ForDemo
{
    public static void main(String[] args)
    {
        int x=1;
        for (System.out.println("a");x<3; System.out.println("c"),x++ )
        {
            System.out.println("d");
        }
    }
}

輸出:

a
d
c
d
c

 

3、初始化表達式和循環后的表達式,是可以不寫的,

但是,初始值定義在for語句外面,以下三段代碼是執行結果是一樣的,只是變量作用域不同

for (int y=0;y<3 ;y++ )
{

}
int y=0;
for (;y<3 ; )
{
  y++
}
int y=0;
for (;y<3 ; y++)
{
}

 

 

 4、無限循環

for (; ; ){ }
while (true){ }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM