繁体   English   中英

Java for循环仅执行一次

[英]Java for loop only executing once

很抱歉提出这样一个基本问题,但此处的其他问题似乎无法解决问题,我已经盯着它看了好一阵子了。 我正在编写一些代码,以查找从1到20的数字的最小公倍数。从调试开始,外部for循环仅运行一次,我不知道为什么。 有人可以指出我对代码视而不见的地方。

public class ED5 {
public static void main(String[] args){
    int smallestCommonMultiple = 1;
    //excluding 1 because it has no effect on the result and would just mean extra work
    int[] numbers = {2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
    //initially set to true for the first loop
    boolean iIsFactor = true;

    //for each potential divisor from 2-20 (note only the prime divisors will ever cause a division)
    for(int i = 2; i < 21; i++){
        while(iIsFactor){
            //reset flag for the start of each new run through the array
            iIsFactor = false;

            //for each element of the array
            for(int j=0; j<19; j++){
                //if the current divisor is a factor of that array entry
                if(numbers[j]% i == 0){
                    //divide the current entry by the current divisor
                    numbers[j] = numbers[j]/i;
                    //indicate that at least one entry had a factor of i
                    iIsFactor= true;
                }
            }//end for loop for each array pass

            if(iIsFactor){
                smallestCommonMultiple *= i;
            }
        }//end while loop for the divisor
    }//end for loop for all the divisors

    //output result
    System.out.println("The smallest common multiple of the numbers from 1 to 20 is:");
    System.out.println(smallestCommonMultiple);
}

}

另一个答案中已经确定了潜在的问题。 这个答案是关于避免使OP看不到哪个循环没有在执行的混乱,从而避免发现错误。

当内部循环是外部循环的整个主体时,可能不清楚哪个循环没有执行。 内循环内部的打印输出和断点对于此目的是无用的。 最简单的解决方案是在外部循环的开始处添加一条语句。 如果该语句执行多次,则是内部循环未执行。 添加的语句几乎可以是任何东西,但是循环迭代的关键变量的打印输出特别有用:

for (int i = 2; i < 21; i++) {
  System.out.println("for-loop, i=" + i);
  while (iIsFactor) {

使用添加的语句运行程序可以很明显地看出,外部循环正在执行全部迭代,问题必须出在内部循环上。

您的while和boolean声明不正确,

for(int i = 2; i < 21; i++){
    //reset flag for the start of each new run through the array
    iIsFactor = false;
    while(!iIsFactor){
while(iIsFactor){
        //reset flag for the start of each new run through the array
        iIsFactor = false;

此后,循环的下一个触发,即while语句变为假。

暂无
暂无

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

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