如何从用户接受整数并将其存储在java中的数组中

时间:2016-04-12 20:00:09

标签: java arrays arraylist

我试图逐个接受用户的原始整数列表,并将其存储到原始数组中供以后使用。 这是我的代码:

     Scanner scanner=new Scanner(System.in);
    int n= scanner.nextInt();
    ArrayList<Integer> arr=new ArrayList<>();
    int[] a = new int[arr.size()];
    Iterator<Integer> iterator = arr.iterator();
    if (n < 15){
        for (int i=0;i<n;i++){
            System.out.println("enter "+i+" th number");
             arr.add(scanner.nextInt());
             a[i] = iterator.next().intValue();

        }} 
    else {
            System.out.println("Please enter number less than 15");
            //break;
        }e here

代码存在运行时错误,如下所示:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at App.main(App.java:26)

我认为这是ArrayList的失败问题(在这种情况下,在迭代arraylist时不允许修改列表)。 如何使上述代码保险???如果我理解我的问题是对的吗? 非常感谢你提前!

3 个答案:

答案 0 :(得分:0)

您无法添加到列表中,然后从该列表上的预先存在的迭代器中读取。

如果您想要添加的元素,请使用

arr[i] = list.get(list.size() - 1);

但是,arr的长度为零,因此arr[i]将产生ArrayIndexOutOfBoundsException

答案 1 :(得分:0)

您的数组的大小应该设置为n个元素,并且您不需要ListIterator来读取Scanner。你需要的只是

Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
    System.out.println("enter " + i + " th number");
    a[i] = scanner.nextInt();
}
System.out.println(Arrays.toString(a));

答案 2 :(得分:0)

您遇到此问题是因为您感谢ArrayList并且iterator同时使用arr.add(scanner.nextInt());阅读iterator。您应该删除arr.get(index)并使用ArrayList访问Sub formatAllCellsAsText() Dim wsTemp As Worksheet Dim LastRow As Long, LastColumn As Long Dim StartCell As Range, Cell As Range Dim Temp As Double Dim Temp2 As String For sht = 3 To Worksheets.Count Set wsTemp = Sheets(sht) Set StartCell = wsTemp.Range("A4") LastRow = wsTemp.Range("A4").CurrentRegion.Rows.Count LastColumn = wsTemp.Range("A4").CurrentRegion.Columns.Count For Each Cell In wsTemp.Range(StartCell, wsTemp.Cells(LastRow, LastColumn)).Cells If Not IsEmpty(Cell.Value) And IsNumeric(Cell.Value) And InStr(wsTemp.Cells(1, Cell.Column), "Client ID") <= 0 Then Temp = Cell.Value Temp2 = Cell.NumberFormat Cell.ClearContents Cell.NumberFormat = "@" Cell.Value = Format(Temp, Temp2) End If Next Next End Sub 的给定元素。