0

Hi I am trying to create a pascal triangle using arraylist, getting concurrent modification exception in line 25 in below code,, please help, i an new in using arraylist. line 25 is.. temp = i.next();

public class PascalT {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner s = new Scanner(System.in);
        System.out.println("enter number");
        int inp = s.nextInt();
        s.close();
        ArrayList<ArrayList<String>> g = new ArrayList<ArrayList<String>>(inp);
        ArrayList<String> t1 = new ArrayList<>();
        t1.add("1");
        t1.add("1");
        g.add(t1);
        int ii = 0;
        ArrayList<String> temp;
        Iterator<ArrayList<String>> i = g.iterator();
        while (i.hasNext() & ii < inp) {
            temp = i.next();
            Iterator<String> i2 = temp.iterator();
            ArrayList<String> tmp = new ArrayList<String>();
            tmp.add("1");
            String temp2 = "";
            while (i2.hasNext()) {
                temp2 = Integer.toString(Integer.parseInt(i2.next())
                        + Integer.parseInt(i2.next()));
                tmp.add(temp2);
            }
            tmp.add("1");
            g.add(tmp);
            tmp.clear();
            ii++;
        }

        for (ArrayList<String> al : g) {
            System.out.println("line");
            String row = "";
            for (String sss : al) {
                row = row + " " + sss;
            }
            System.out.println(row);
        }
    }
}
Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
user2054151
  • 7
  • 1
  • 12
  • I think there are a few easier ways to do a pascal triangle. – Yassin Hajaj Dec 08 '15 at 23:38
  • @DevilsHnd Nope, just read the answer below. – Yassin Hajaj Dec 08 '15 at 23:38
  • True enough...removed my comment. Thank you. – DevilsHnd - 退職した Dec 08 '15 at 23:40
  • I've removed the Pascal tag, as your question has absolutely nothing to do with the Pascal programming language. Tags here have **specific** meanings. Please read the description of any tag before using it so you understand that **specific** meaning and can see if it applies to your question, instead of just adding those that have words that seem familiar to you or have a different meaning than that of the tag. Thanks. – Ken White Dec 09 '15 at 15:05

1 Answers1

1

You cannot modify a list while iterating through it. You i is an iterator over g. At the end of the loop, when you do g.add(tmp), it makes the iterator invalid, and next time you try to use it, you get an exception.

I would suggest a way to fix it for you, but your choice of variable names is horrible, I have no idea what your code is doing, and I am too lazy to to figure it out. I think, simply getting rid of i and replacing temp = i.next() with g.get(ii) should do the trick.

Dima
  • 39,570
  • 6
  • 44
  • 70