如何将这些语句更改为嵌套的while语句?

时间:2014-10-21 04:08:39

标签: java for-loop while-loop

我正在尝试将嵌套的for循环更改为嵌套的while循环。我尝试了几种不同的方法,但每次尝试都无法得到预期的结果:T = 1 T = 1 T = 2 T = 4 T = 5 T = 11 R = 30

    public static void main(String[] args)
    {
        int s = 0;
        int t = 1;
        //first for-loop i'm trying to make a while-loop
            for (int i = 0; i < 5; i++)
             {
                s = s + i;
                //second for-loop i'm trying to make a while-loop
                for (int j = i; j > 0; j--)
                {
                   t = t + (j-1);
                }
                s = s + t;
                System.out.println("T is " + t);
            }
        System.out.println("S is " + s);
    }

4 个答案:

答案 0 :(得分:4)

试试这个:

public static void main(String[] args)
    {
        int s = 0;
        int t = 1;
        int i=0;
        //first for-loop i'm trying to make a while-loop
           while(i<5)
         {
            s = s + i;
            int j=i;
            //second for-loop i'm trying to make a while-loop
            while(j>0)
            {
               t = t + (j-1);
               j--;
            }
            s = s + t;
            System.out.println("T is " + t);
            i++;
        }
        System.out.println("S is " + s);


}

答案 1 :(得分:1)

请参阅下面的内联评论:

    int s = 0;
    int t = 1;
    int i = 0; // init i outside the while-loop
    while (i < 5) // replaces for-loop stop condition
    {
        s = s + i;
        int j = i; // init j outside the while-loop
        while (j > 0) // replaces for-loop stop condition
        {
            t = t + (j-1);
            j--; // decrement j
        }
        s = s + t;
        System.out.println("T is " + t);
        i++; // increment i
    }
    System.out.println("S is " + s); 

<强>输出

T is 1
T is 1
T is 2
T is 5
T is 11
S is 30

答案 2 :(得分:1)

一般情况下,转

for (int i = 0; i < 5; i++) {
    // stuff goes here
}

进入while循环,在它之前移动初始化,将条件置于while条件下,并在循环中将增量(或其他更改步骤)放在最后。

int i = 0;
while (i < 5) {
    // stuff goes here
    i++;
}

同样的逻辑也适用于你的内循环。

答案 3 :(得分:0)

所有的初始化语句都放在while循环的起始块之前,所有的incremental / updation语句都只在底部执行,循环中放置了闭合块!那么,只需在循环体之前移动初始化并在退出循环之前推送增量/减量操作......

转换后的答案是: -

int i=0;
while(i<5)
         {
            s = s + i;
            //second for-loop i'm trying to make a while-loop
            int j=i;  
            while(j>0)
            {
               t = t + (j-1);
               j--;
            }
            s = s + t;
            System.out.println("T is " + t);
            i++;
        }