Page 1 of 1

About Question enthuware.ocpjp.i.v11.2.1454 :

Posted: Fri Nov 20, 2020 8:28 am
by Michalrk1978
I think, it is also possible to use an enhanced for loop for all the tasks (also task 2 and 3). Of course, that doesn't make sense.
An example solutions is presented below.

Code: Select all

    public static void main(String args[]) {
        String[] array = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"};

        for (String x : array) {
            System.out.println(x);
        }

        int i = array.length - 1;
        for (String x : array){
            System.out.println(array[i]);
            --i;
        }

        i = 0;
        for (String x : array){
            if(i%2 == 0) {
                System.out.println(array[i]);
            }
            ++i;
        }
    }

Re: About Question enthuware.ocpjp.i.v11.2.1454 :

Posted: Fri Nov 20, 2020 9:57 am
by admin
Yes, if you use additional loop variable(s), then it is possible but that has nothing to do with the for-each loop.
Your example does not really iterate the array using the for-each loop. You are using the for each loop to modifying the loop variable i, which is used to access the array elements.

Anyway, for the purpose of the exam, if you see a similarly worded question, you should select the options given in this question.