Smyčky while

Intermediate Java

Jim White

Java Developer

Jak funguje smyčka while

  • Nejprve se vyhodnotí podmínka
    • Je-li splněna, kód se spustí
    • Pokud ne, smyčka skončí
  • Opakování: vyhodnocení podmínky a rozhodnutí

Schéma smyčky while

Intermediate Java

Syntaxe smyčky while

while (condition) {

  // Run this code

}
  • Syntaxe podobná příkazu if
  • Na rozdíl od if se může spustit vícekrát
Intermediate Java

Příklad smyčky while

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

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

Nekonečná smyčka while

  • Zapomenutá aktualizace proměnné
int counter = 1;

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

 

➡ Program přestane reagovat

  • Podmínka je vždy true
int counter = 1;

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

Aktualizační operátory

int counter = 0;

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

Podobně platí pro -=, *=, /=, ...

Intermediate Java

Break

  • Pomocí break lze předčasně ukončit smyčku while, ale není to osvědčený postup
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
Intermediate Java

Rekapitulace

// 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;
  }
}
Intermediate Java

Pojďme si procvičit!

Intermediate Java

Preparing Video For Download...