簡體   English   中英

打印ArrayList的元素

[英]Printing the elements of an ArrayList

import java.util.*;

public class Prog1 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter the value:");
        Integer v = in.nextInt();

        System.out.println("Enter number of elements:");
        int n = in.nextInt();

        ArrayList<Integer> a = new ArrayList(Prog1.duplica(v, n));

        for(int i = 0; i < a.size(); i++) {
            System.out.println(a.get(i));
        }
    }

    public static ArrayList<Integer> duplica(Integer v, int n) {
        ArrayList<Integer> a = new ArrayList();

        for(int i = 0; i < n; i++) {
            a.set(i, v);
        }

        return a;
    }

}

此方法應要求一個整數值和在arraylist中共同包含的元素數,然后應打印它們。 例如,如果用戶插入“ 5”和“ 4”,則應打印“ 5 5 5 5”。 該程序會詢問用戶兩個數字,但會出現此錯誤:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:372)
    at java.base/java.util.ArrayList.set(ArrayList.java:472)
    at Prog1.duplica(Prog1.java:20)
    at Prog1.main(Prog1.java:11)

您正在嘗試使用set方法將項目添加到空列表。 set應該替換指定索引處的現有值。 由於您的列表為空,因此沒有可替換的值,從而在嘗試訪問第一個元素時導致IndexOutOfBoundsException

使用add代替:

for(int i=0; i<n; i++) {
  a.add(v);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM