2017-10-17 99 views
0

早上好, 我是编程新手。 我想写一个程序,它从键盘读取一些数字并将它们相加。我到达写一个程序,总结数字,我的问题是,我不知道如何配置扫描仪来填充数组/ ArrayList。 我怎么办? 这是我的代码。从Java键盘填充数组

class array { 
public static void main(String[] args) { 
    int start = 0; 
    int [] interi = {2,3,6,10,24,45}; 

    for (int i:interi) 
     start+=i;   //++ 

    System.out.println(start); 
    } 

} 

回答

0

我不知道如何将扫描仪配置,以填补数组/ ArrayList中。我怎么办?

要作为用户被提示填充一个ArrayList:

//example, prompt user 3 times 
ArrayList<Integer> list = new ArrayList<>(); 
for(int i=0; i<3; i++) 
    list.add(scn.nextInt()); 

如果使用数组:

array[i] = scn.nextInt(); 

然而,请注意该阵列具有固定的大小。所以你不想提示超过给定的数组大小。

如果要提示用户未知次数,请在数组列表中使用while循环。