Sha*_*nix 5 java arrays while-loop joptionpane
这是我的第一篇文章因此不要踩我,如果我写了一些愚蠢的事.
我刚刚开始上课,今天在"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));
}
}
Run Code Online (Sandbox Code Playgroud)
问题是循环用很多零填充数组,导师结果的屏幕截图显示了一个只列出除数的窗口.
我尝试用ArrayList做到这一点,但这对我来说是黑魔法,而我的导师并没有告诉我们如何使用除了代码中使用的东西之外的任何东西.
任何帮助高度赞赏.
您遇到的主要问题是您想要打印未知数量的值,但您使用数组来存储它们,并且数组具有固定大小。由于您有一个 数组int,因此它将完全填充默认值零。
理想情况下,您只打印数组的第一组非零值,但您要存储分散在数组中的除数。
dvr[x] = x;将每个值存储在该值的索引处,而实际上您应该将每个新值存储到数组中的下一个空位中。
创建一个单独的索引变量,并使用它存储每个值:
int index = 0;
while (x >= 2 && x <= d) {
...
if (y == 0) {
dvr[index++] = x;
...
Run Code Online (Sandbox Code Playgroud)
然后,当主循环完成后,您可以创建一个新的“显示数组”,其中仅包含除数,而不包含零。此时,index准确地告诉您它需要有多大:
int[] display = Arrays.copyOf(dvr, index);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(display));
Run Code Online (Sandbox Code Playgroud)