简体   繁体   中英

Print ArrayList of Arrays in Java

I created an ArrayList of arrays, but I don't know how to print them. Here's what I am trying to do:

    int j=0;
    for (int i=0; i<aArray.length-1; i++){
        exp=new int[100];
        if (Character.isDigit(aArray[i])){
            if(Character.isDigit(aArray[i])==true &&  aArray[i-1]=='-'){
                exp[j]=Character.getNumericValue(-(aArray[i]));
            }
            else{
                exp[j]=Character.getNumericValue(aArray[i]);
            }
            System.out.print(exp[j]);

            j++;   
        }
    }
    System.out.println(" ");
    list.add(exp);
}
for (int i=0; i<5; i++){
    System.out.println(list.get(i)[i]);
}  

All I get is 5 zeros. What am I missing? Practically, I read a .txt file in my program, and all I want to do, is seperate and write the numbers of each in the exp[] arrays and then save them in list (ArrayList of Arrays).

Add a for loop to go through each array in the list too:

for (int i=0; i<5; i++){
    int[] tmp = list.get(i);
    for (int j=0; j<tmp.length; j++) {
         System.out.println(tmp[j]);
    }
}

edit: You also need to be adding the array to the arraylist inside the for loop, otherwise you're adding a null array.

for (int i=0; i<aArray.length-1; i++){
    exp=new int[100];
    if (Character.isDigit(aArray[i])){
        if(Character.isDigit(aArray[i])==true &&  aArray[i-1]=='-'){
            exp[j]=Character.getNumericValue(-(aArray[i]));
        }
        else{
            exp[j]=Character.getNumericValue(aArray[i]);
        }
        System.out.print(exp[j]);

        j++;   
    }
    System.out.println(" ");
    list.add(exp);
}

Problem solved guys, I just needed to initialize exp array outside "for" loop, place a "while" loop and that's all! Thank you for your answers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM