Извините, что задал такой базовый вопрос, но другие вопросы здесь, похоже, не устраняют проблему, и я долго смотрел на нее. Я пишу код, чтобы найти наименьший общий кратный для чисел от 1 до 20. От отладки внешний цикл for работает только один раз, и я не могу понять, почему. Может кто-то, пожалуйста, указать, куда я пошел слепой код.Java for loop только один раз
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);
}
}
Почему вы так думаете? Проходит 19 раз для меня. –
'Sysout' печатает только один раз ... –
Я пробовал его несколько раз и прошел через отладчик, а внешний цикл for запускался только один раз. Печать должна только один раз. –