User Tools

Site Tools


java:loop_statements

This is an old revision of the document!


Εντολές ανακύκλωσης

While και do-while statements

WhileDemo.java
class WhileDemo {
    public static void main(String[] args){
        int count = 1;
        while (count < 11) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}
DoWhileDemo.java
class DoWhileDemo {
    public static void main(String[] args){
        int count = 1;
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}

For statement

Η εντολή for συντάσσεται όπως και στην γλώσσα προγραμματισμού C.

ForDemo.java
class ForDemo {
  public static void main(String[] args){
    int[] numbers = {1,2,3,4,5,6,7,8,9,10};
    for (int i=0; i<numbers.length;i++) {
      System.out.println("Count is: " + numbers[i]);
    }
  }
}

Ενδιαφέρον έχει μία διαφοροποιημένη έκδοση της for που υποστηρίζει η Java με σκοπό την ανακύκλωση σε όλα τα μέλη ενός πίνακα (ή ενός Collection όπως θα δούμε αργότερα). Δείτε το παρακάτω παράδειγμα, χρήσης του συγκεκριμένου τελεστή για την ανακύκλωση στα μέλη ενός πίνακα.

EnhancedForDemo.java
class EnhancedForDemo {
  public static void main(String[] args){
    int[] numbers = {1,2,3,4,5,6,7,8,9,10};
    for (int item : numbers) {
      System.out.println("Count is: " + item);
    }
  }
}
java/loop_statements.1442573532.txt.gz · Last modified: 2015/09/18 09:52 (external edit)