I need to print the output whereby when

`````` int x = 1, it will be show the first 4 elements in the arrayList.
int x = 2, it will be show the first 6 elements in the arrayList.
int x = 3, it will be show the first 8 elements in the arrayList.
``````

shown below is my code. It's probably not optimal solution and I would like to know how can I improve on it. Thanks

``````import java.util.ArrayList;

public static void main(String[] args) {
int x = 0;
ArrayList numbers = new ArrayList();

while(x < 4) {
if(x == 1) {
for(int i = 0; i < 4; i++) {
System.out.println(numbers.get(i));
}
}

if(x == 2) {
for(int i = 0; i < 6; i++) {
System.out.println(numbers.get(i));
}
}

if(x == 3) {
for(int i = 0; i < 8; i++) {
System.out.println(numbers.get(i));
}
}
x++;
}
}
``````

Hmm.. In what sense do you want it to be improved?

At least, the add() part can be improved by using a for-loop. I am not sure why you need a while-loop to display that? You could simply take out the existing for loop and use it to print the output you want because each of those if statment condition are mutual exclusive and doesn't really have anything to do with the value of x. Unless you are going to have a dynamic value of x (by getting it from user input), you may use if-statement to deal with x value.

For x = 1,2,3 you display 4,6,8 elements.

No need for those if tests. You can do that in a single loop if you use a simple formula to covert 1,2,3 into 4,6,8,,, eg multiply by 2 and add 2.