繁体   English   中英

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

[英]How can i change these for statements to nested while statements?

我正在尝试将嵌套的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); } 

尝试这个:

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);


}

请参阅下面的内联评论:

    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

一般来说,转

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

进入while循环,您将初始化移到它的前面,将条件放入while作为条件,最后将增量(或其他更改步骤)放入循环内。

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

同样的逻辑也应适用于您的内部循环。

所有初始化语句都放在while循环的开始块之前,而所有增量/更新语句都在循环将其结束块放置的底部执行! 所以,只需在循环体之前移动初始化并在退出循环之前推送增量/减量操作...

转换后的答案将是:

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++;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM