-2

Here my arraylist contains number from 1 to 100.

[1, 2, 3, 4, 5, 6, 7, 8, 9,10....100] 

Here is my code.

public class Myclass {
    static int GG_NUm=5;
    static final String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    static ArrayList a;
    public static void main(String[] args) {
        a = new ArrayList();
        for (int i = 1; i <= 100; i++) 
            a.add(i);

        System.out.println(a);
        mylist();
    }

    public static void mylist() {
        if(a.size() != 0){
            String s="";
            int shifting=0;

            //System.out.println(a.size());
            if (a.size() >= GG_NUm){
                shifting = GG_NUm;
                for (int j = 0; j< GG_NUm; j++){
                  if (j != GG_NUm-1)

                      {s = s + a.get(j) + ',';
                  //System.out.println(s);
                      }
                  else
                    s = s +a.get(j);
                  //System.out.println(s);
                }
              }
              else{
                shifting = a.size();
                for (int j = 0; j< a.size(); j++){
                  if (j != a.size() - 1)
                  {
                    s = s+a.get(j) + ',';
                  //System.out.println(s);
                  }
                  else
                  {
                    s = s + a.get(j);
                    //System.out.println(s);
                  }

                }
              }
        }
    }
}

I am getting output

1,
1,2,
1,2,3,
1,2,3,4,
1,2,3,4,5

I want to get output like

1,2,3,4,5
6,7,8,9,10
11,12,13,14,15

Until the whole arraylist ends.

Here I am taking int in arraylist, it may be alphanumeric.

Help.

Thanks.

Sergei Bubenshchikov
  • 5,275
  • 3
  • 33
  • 60
Vince
  • 21
  • 1
  • 3

1 Answers1

1

You have to use the modulo-operator (%) to check if your index divides 5

for(int i = 0; i<a.size(); i++){
   System.out.print(a[i]+",")
   if(i%5==0) System.out.println();
}

Check the usage of the %-operator here: Modulo operator

If the main problem is to iterate a collection (e.g. ArrayList), check this link: Iterate a Collection

Community
  • 1
  • 1
osanger
  • 2,276
  • 3
  • 28
  • 35