为什么我的数组只保存我输入的最后一个数字?


我的代码是:
int total = 10;
int[] myArray = new int [total];
System.out.println("Enter numbers.  To stop, enter 0.")
int numbers = input.nextInt();
while (numbers != 0) {
     for (int i = 0; i < total; i ++)
          myArray[i] = numbers;
     numbers = input.nextInt();
}
for (int i = 0; i < myArray.length; i++)
     System.out.print(myArray[i] + ", ") //This line only prints the last number I enter 10 times.

我希望能够用我输入的数字打印整个数组。例如:

输入:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0

但结果是:10, 10, 10, 10, 10, 10, 10, 10, 10, 10

编辑:我不明白为什么我的问题被标记为重复?我试着在这个网站上到处搜索类似的问题,但没有找到一个,所以这就是我问的原因。这不就是这个网站的目的吗?编辑2:好吧。我明白了。我会把我的问题带到其他一些更有用的网站。感谢您的"服务"栈交换

for循环每次都重置数组中的所有项。我怀疑你是不是故意的。

你可以这样做:

  1. 声明iwhile循环外,用0初始化。
  2. while循环的条件更改为numbers != 0 && i < total
  3. 删除while循环中的for循环
  4. 直接写myArray[i] = numbers;i++;来代替for循环。

代码如下:

int numbers = input.nextInt();
int i = 0;
while (numbers != 0 && i < total) {
    myArray[i] = numbers;
    i++;
    numbers = input.nextInt();
}

这是你的代码运行良好

最新更新