简体   繁体   中英

How to store this pattern in Java arraylist?

I want to store the below array pattern in List, I am not understanding how to implement this as it has alternate increment.

  1. Increment the number by 399.
  2. Increment by 1

and continue the above 2 steps for a certain length of numbers. If someone can guide me for the logic with simple OOPs concepts

0, 400, 401, 800, 801, 1200, 1201, 1600, 1601, 2000

You could also do something like this:

//add the first item outside of the loop, so that you can access the previous item within it
list.add(1)

//loop through the list in increments of 2
for (int i = 1; i < length; i += 2) {
   list.add(list.get(i - 1) + 399);
   list.add(list.get(i) + 1);
}

Figured it out, this is what I wrote now, and it workds

int pages = 8;

    List<Integer> numArray = new ArrayList<Integer>();
    
    numArray.add(0);

    boolean incrementFlag = false;
    int i = 400;
    for (int j = 0; j < (pages-1); j++) {

        numArray.add(i);
        if (incrementFlag)
            i += 399;
        else
            i += 1;

        incrementFlag = !incrementFlag;

    }

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