-2

I'm really new to Java, and was wondering if someone could help me convert the following to foreach loops into for loops?

Assuming expression is a collection of items:

for(Type x: expression){
   ...
   for(Type y: x.expression){
     .....
    }
}
TestNInja
  • 167
  • 1
  • 15
  • If `x` is an `int` it doesn't make sense. `x` supposed to be Iterable according to this code. – SHG Jun 06 '17 at 00:05
  • The code in the question won't compile (`for(int y: x){...}`) because `x` is an `int`. Is this code you just came up with or did you copy it from somewhere? – Radiodef Jun 06 '17 at 00:05
  • 1
    I just modeled the loop after something else I am working on, was looking for a general solution. Edited the condition with different type – TestNInja Jun 06 '17 at 00:06
  • First come up with something that compiles. – DevilsHnd Jun 06 '17 at 00:07

1 Answers1

0

expression needs to be some kind of collection of items. The for (Type item : items) loop just iterates over all of them.

To manually loop over the collection you just need the length of the collection and can use:

for (int i = 0; i < collection.size(); i++) { // or .length() if it is an array
  Type item = collection.get(i); // or collection[i] if it is an array
}

Type needs to be the type of the items in the collection.

schrej
  • 450
  • 4
  • 10
  • How would having a nested foreach loop work in this case? – TestNInja Jun 06 '17 at 00:09
  • 1
    Well just nest them. If `Type` is another collection it will work the same way. Just use something other than `i` (e.g. `j`) for the nested loop or it'll get overwritten. – schrej Jun 06 '17 at 00:09
  • 1
    An enhanced `for` statement does *not* get translated by the compiler to a `for` loop with index variable, because that will not perform for non-array based lists, and don't even work for other types of collections, because they don't have a `get(int)` method. – Andreas Jun 06 '17 at 00:17