Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1454 :

Posted: Sat Sep 16, 2017 3:39 am
by fanfa86
Why enhanced for loop can not be used for task 3?

This could work:

Code: Select all

public class HelloWorld{

     public static void main(String []args){
        String[] array = {"0","1","2","3","4","5"};
        int i = 0;
        for(String v : array){
            if (i % 2 == 0){
                System.out.println(v);
            }
            i++;
        }
     }
}
$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
0
2
4

Re: About Question enthuware.ocajp.i.v8.2.1454 :

Posted: Sun Sep 17, 2017 10:31 am
by admin
You are not using just the enhanced for loop in your code. You are using iteration variable as well. That is the whole point of this question. Enhanced for loop does not have an iteration variable.

Re: About Question enthuware.ocajp.i.v8.2.1454 :

Posted: Sun Nov 11, 2018 10:56 am
by flex567

Code: Select all

You are using iteration variable as well.
There is no mention that you cant use iteration variable.

Re: About Question enthuware.ocajp.i.v8.2.1454 :

Posted: Sun Nov 11, 2018 8:57 pm
by admin
That is the whole point of this question. Enhanced for loop does not have an iteration variable. Otherwise, all loops are interchangeable. What you can do with one loop, you can do with another.

Re: About Question enthuware.ocajp.i.v8.2.1454 :

Posted: Mon Feb 24, 2025 5:31 pm
by shear12345
You might want to add something to the effect of "without any additional code other than the loop and it's body", because you could use a stream to reverse the array or filter out odd objects before using the enhanced for-loop to achieve all 3.