很抱歉提出这样一个基本问题,但是这里的其他问题似乎无法解决问题,而且我已经盯着它看了很长一段时间。我正在编写一些代码来查找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);
}
}
答案 0 :(得分:4)
另一个答案已经确定了潜在的问题。这个答案是关于避免混淆,阻止OP看到哪个循环没有执行,因此无法找到错误。
当内循环是外循环的整个主体时,可能不清楚哪个循环没有执行。内环中的打印输出和断点对此无用。最简单的解决方案是在外部循环的开头添加一个语句。如果该语句多次执行,则内循环不执行。添加的语句几乎可以是任何内容,但是循环迭代的关键变量的打印输出特别有用:
for (int i = 2; i < 21; i++) {
System.out.println("for-loop, i=" + i);
while (iIsFactor) {
使用添加的语句运行程序显然外部循环正在进行完整的迭代集,问题必须是内部循环。
答案 1 :(得分:2)
你的while和boolean声明不正确,
public enum JobStatus implements Serializable{
INCOMPLETE,
INPROGRESS,
ABORTED,
COMPLETED;
public String getStatus() {
return this.name();
}
}
答案 2 :(得分:2)
while(iIsFactor){
//reset flag for the start of each new run through the array
iIsFactor = false;
在此之后,循环的下一个itteration,while语句变为false。