0

I want to write anything that is in arraylist irrespective of its size in this manner in the csv but one array has less values it causes an array out of bounds error is there any way to work around this?

In this A to H it has it's own arraylist, sometimes the other arrays have less elements in it than size of A this causes array out of bounds.

try{
        File file = new File("aaaa.csv");
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
    
        for(int j=0;j<A.size();j++) {
            bw.write(A.get(j));
            bw.write(","+B.get(j));
            bw.write(","+C.get(j));
            bw.write(","+D.get(j));
            bw.write(","+E.get(j));
            bw.write(","+F.get(j));
            bw.write(","+G.get(j));
            bw.write(","+H.get(j));
            bw.newLine();
        }
        bw.close();
        fw.close();
         
    }
    catch(IOException e) {
        e.printStackTrace();
    }
3
  • In this A to H it has it's own arraylist Out of interest - why? Commented May 24, 2022 at 14:14
  • It basically is extracting info from a file based on specific topic storing into its specific arraylist Commented May 24, 2022 at 15:48
  • If A-H have come from one file, this has an aroma of something being done in the wrong way ;) (On the basic of the old saying data that belong together should be together) Commented May 24, 2022 at 15:57

1 Answer 1

1

You should compare a list size with the current value of the index j

for (int j = 0; j < A.size(); j++) {  
  bw.write(A.get(j));  
  bw.write("," + (B.size() > j ? B.get(j) : ""));  
  bw.write("," + (C.size() > j ? C.get(j) : ""));  
  bw.write("," + (D.size() > j ? D.get(j) : ""));  
  bw.write("," + (E.size() > j ? E.get(j) : ""));  
  bw.write("," + (F.size() > j ? F.get(j) : ""));  
  bw.write("," + (G.size() > j ? G.get(j) : ""));  
  bw.write("," + (H.size() > j ? H.get(j) : ""));  
  bw.newLine();  
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.