这是我的第一篇帖子,如果我写了什么蠢话,请不要骂我。
我刚开始上IT课程,今天在“while”循环课上,我的导师给我们布置了以下作业:
编写一个程序,该程序读取自然数n,并在一个图形框中显示出它在区间[2; n-1]中的所有因子。
到目前为止,我想出了一个可行的代码,但结果有点错误:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[x] = x;
x = x + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(dvr));
}
}
问题在于该循环用许多零填充了数组,导师的结果截图显示了仅列出因子的窗口。
我尝试使用ArrayList来解决这个问题,但对我来说那是黑魔法,而且我的导师还没有教我们如何使用代码中未涉及的任何东西。
非常感谢任何帮助。