2016-09-25 48 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的代碼工作正常。

相關問題