This site requires JavaScript, please enable it in your browser!
Greenfoot back
saady
saady wrote ...

2020/12/9

Loops

saady saady

2020/12/9

#
For my project, I have to use a while loop or for loop. I'm not sure what I would use a loop for. Does anybody know what I can use a loop for?
RcCookie RcCookie

2020/12/9

#
for loops are mostly used for iterating through arrays, lists and other iterable data types. For example:
int[] array = new int[] {5,4,3,2,1};
for(int i=0; i<array.length; i++) {
    System.out.println(array[i]);
}
Often you can also use the so called foreach loop:
for(int element : array) {
    System.out.println(element);
}
The while loop is usually used in cases where you do the same thing all over again many times, without the need of a counting variable. For example, move until you hit something:
while(getOneIntersectingObject(Wall.class) == null) {
    move(1);
}
saady saady

2020/12/9

#
Thanks, I think I know what I can use a while loop for now.
You need to login to post a reply.