2016-09-25 49 views
-5

我的代码是:我的数组是如何保存我输入的最后一个数字的?

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:好。我明白了。我会把我的问题带到其他更有用的网站。感谢您的“服务”堆栈交换。

+0

你认为你的for循环做什么? –

+0

从你的代码,我的理解,你可能会尝试输入,直到用户输入'0',或者你的数组已满?我对吗? –

+0

+穆罕默德是的。这就是我想要的。 – 5120bee

回答

1

您的for循环每次都重置数组中的所有项目。我怀疑你是否打算这么做。

+0

我明白了。但是,如果我在while循环中取出输入行,当用户输入'0'时,如何停止循环? – 5120bee

+0

您的while循环中的数字!= 0是正确的,您只需删除while循环中的for循环并添加另一个条件来检查用户是否已经填充了所有数组。像while(数字!= 0 ||计数器<总数) 然后ofcourse你必须分配输入到你的数组并更新计数器 –

0

你可以这样做:

  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(); 
} 

Here的代码工作正常。

相关问题