1. 程式人生 > >Java關於for與while迴圈的區別我的理解

Java關於for與while迴圈的區別我的理解

有很多帖子寫for迴圈與while迴圈的區別是迴圈變數的差異,引用其他人的原話,貼一張截圖,他們大多是這樣描述的 這裡寫圖片描述 1. 個人認為上圖所述的從記憶體角度考慮,for迴圈既可以使用區域性變數,也可以使用外部變數,而while迴圈的終止條件則必須是外部變數。下面是都是用外部變數的測試片段

@org.junit.Test
    public void testForWhile() {
        // 方式1
        int i = 5;
        for (; i < 10; i++) {
            System.out.print("-");
        }
        System.out.println(i);
        // 方式2
int j = 5; while (j < 10) { System.out.print("-"); j++; } System.out.println(j); } /** result: -----10 -----10 */

可見,並不是說for迴圈不能使用外部變數;但是for迴圈的確可以使用區域性變數,這也是用的最頻繁的方式。 2. 再者從需求場景考慮,不知道迴圈多少次,用while迴圈;知道迴圈次數則用for迴圈。這句話個人理解,for迴圈照樣能實現while迴圈的需求, 測試程式碼如下:

@org.junit.Test
    public void testForWhile2() {
        // 方式1
        int i = 5;
        for (;true; i++) {
            System.out.print("-");
            if (i>10) {
                break;
            }
        }
        System.out.println(i);
        // 方式2
        int j = 5;
        while (true
) { System.out.print("-"); if (j>10) { break; } j++; } System.out.println(j); } /** result: -------11 -------11 */

所以for迴圈能夠實現while迴圈的功能,但while迴圈不能採用迴圈內的區域性變數作為終止條件。但為什麼有的時候又要用while迴圈呢?個人覺得是因為看起來更簡潔,邏輯更清晰。

總之總結一句話,for迴圈與while不同在於for迴圈可以採用區域性變數作為迴圈變數,其他在功能實現上誰看起來更簡潔清晰就用誰。