Else, else if

Java voor gevorderden

Jim White

Java Developer

Meerdere if's

if (score >= 90) {
  System.out.println("Excellent!");  
}

if (score >= 70) {
  System.out.println("Good effort.");  
}

if (score < 70) {
  System.out.println("Keep trying!");  
}

Als score >= 70, worden zowel Excellent! als Good effort. geprint

➡ Meerdere if-statements kan rommelig worden

Java voor gevorderden

if - else if - else

int score = 80;

if (score >= 90) { 
  System.out.println("Excellent!");  
} else if (score >= 70) { 
  // Only this code is executed
  System.out.println("Good effort.");  
} else {
  System.out.println("Keep trying!");  
}
Good effort.
int score = 60;

if (score >= 90) {
  System.out.println("Excellent!");  
} else if (score >= 70) { 
  System.out.println("Good effort.");  
} else { // Only this code is executed
  System.out.println("Keep trying!");  
}
Keep trying!
Java voor gevorderden

Slechts één blok draait

int score = 95;

if (score >= 90) { // Only this code is executed
  System.out.println("Excellent!");  
} else if (score >= 70) { 
  System.out.println("Good effort.");  
} else {
  System.out.println("Keep trying!");  
}
Excellent!
Java voor gevorderden

Zoveel als nodig—let op de volgorde

// Zoveel als we willen
if (score >= 95) { 
  System.out.println("Excellent job, well done!");  
} else if (score >= 90) { 
  System.out.println("Excellent!");  
}  else if (score >= 80) { 
  System.out.println("Great job.");  
}  else if (score >= 70) { 
  System.out.println("Good effort.");  
} else {
  System.out.println("Keep trying!");  
}
// Let op de volgorde
int score = 95;

if (score > 70) { // Deze code draait
  System.out.println("Good effort.");  
} else if (score >= 90) { 
  // Dit is ook geldig
  System.out.println("Excellent!");  
} else {
  System.out.println("Keep trying!");  
}
Good effort.
Java voor gevorderden

Samenvatting

int age = 33;

if (age < 20) {
    System.out.println("You are a teenager");
} else if (age < 30) {
    System.out.println("You are in your twenties");
} else if (age < 40) { // Only this code block will be executed
    System.out.println("You are in your thirties");
} else {
    System.out.println("You are older than 39");
}
You are in your thirties
Java voor gevorderden

Laten we oefenen!

Java voor gevorderden

Preparing Video For Download...