Perulangan while

Java Menengah

Jim White

Java Developer

Cara kerja while

  • Pertama, periksa kondisi
    • Jika benar, jalankan kodenya
    • Jika tidak, perulangan berhenti
  • Ulangi: periksa kondisi lalu putuskan

Skema perulangan while

Java Menengah

Sintaks while

while (condition) {

  // Run this code

}
  • Sintaks mirip dengan pernyataan if
  • Berbeda dari if, dapat berjalan berulang kali
Java Menengah

Contoh while

// Prints numbers smaller than 5
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter + 1;
}
1
2
3
4
Java Menengah

Perulangan while tak berujung

  • Lupa memperbarui variabel
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter + 0;
}

 

➡ Menyebabkan program macet

  • Kondisi selalu true
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter - 1;
}
Java Menengah

Operator pembaruan

int counter = 0;

// Same as counter = counter + 3
counter += 3;

Mirip dengan -=, *=, /=, ...

Java Menengah

Break

  • Kita dapat memakai break untuk keluar dari while lebih awal, namun ini bukan praktik terbaik
int counter = 1;
while (counter < 5){
    System.out.println("Counter: " + counter);
    if (counter == 3) {
        break; // Exit the loop when counter is 3
    }
    counter+=2;
}
Counter: 1
Counter: 3
Java Menengah

Ringkasan

// while loop that prints even numbers smaller than 20
int counter = 2;

while (counter < 20){
  System.out.println(counter);
  counter *= 2;

  // Exit while loop if counter is odd
  if (counter % 2 == 1){ // counter % 2 is counter modulo 2
    System.out.println("Something went wrong, counter is odd.");
    break;
  }
}
Java Menengah

Ayo berlatih!

Java Menengah

Preparing Video For Download...