2017-01-26 70 views
-2

我試圖用.length輸入數組的長度,但弄錯了。 什麼是錯的?如何輸入數組長度?

import java.util.*; 
public class Storage { 
public static int i = 0, size; 
static int[] number; 

public static void main (String[] args) { 
    Scanner input = new Scanner(System.in); 
    System.out.println("What is the value of array?"); 
    number = new int [input.nextInt()]; 
    System.out.println("Write the numbers:"); 

    for (int i : number) { 
     number[i] = input.nextInt(); 
    } 
    System.out.println("Array:"); 
    System.out.println(Arrays.toString(number)); 
} 

} 

,輸出是:

What is the value of array? 
3 
Write the numbers: 

1 
2 
3 
Array: 
[3, 0, 0] 
+2

'的for(int i = 0; i

+0

你試過'lengh'或'length'嗎? – alayor

+0

兩者,但沒有結果 – Nina

回答

0

你是不是增加索引,所以存儲所有值,您在第0 index.Try由此進入:

 for (int i = 0; i < number.length; i++) { 
     number[i] = input.nextInt(); 
    } 

    System.out.println("Array:"); 

    for (int j : number) { 
     System.out.println(j); 
    } 

輸出:

What is the value of array? 
3 
Write the numbers: 
1 
2 
3 
Array: 
1 
2 
3 
0

的foreach用於在收集讀數值。

改爲使用它。

for(int k = 0;k<numbers.length;k++) 
{ 
    numbers[k] = input.nextInt(); 
} 
相關問題