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();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    numbers.add(5);
    numbers.add(6);
    numbers.add(7);
    numbers.add(8);
    numbers.add(9);
    numbers.add(10);
    numbers.add(11);    
    numbers.add(12);
    numbers.add(13);
    numbers.add(14);
    numbers.add(15);

    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.

Edited 2 Years Ago by Taywin

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.

This article has been dead for over six months. Start a new discussion instead.