我的代码是:
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
for循环每次都重置数组中的所有项。我怀疑你是不是故意的。
你可以这样做:
- 声明
i
在while
循环外,用0
初始化。 - 将
while
循环的条件更改为numbers != 0 && i < total
。 - 删除
while
循环中的for
循环 - 直接写
myArray[i] = numbers;
和i++;
来代替for
循环。
代码如下:
int numbers = input.nextInt();
int i = 0;
while (numbers != 0 && i < total) {
myArray[i] = numbers;
i++;
numbers = input.nextInt();
}
这是你的代码运行良好