Else, else if

Средний уровень Java

Jim White

Java Developer

Несколько операторов if

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

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

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

Если score >= 70, выводятся и Excellent!, и Good effort.

➡ Несколько операторов if могут усложнить код

Средний уровень Java

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

Выполняется только один блок

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

Блоков может быть сколько угодно — главное, порядок

// As many as we want
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!");  
}
// Be careful with the order
int score = 95;

if (score > 70) { // This code runs
  System.out.println("Good effort.");  
} else if (score >= 90) { 
  // This is also valid
  System.out.println("Excellent!");  
} else {
  System.out.println("Keep trying!");  
}
Good effort.
Средний уровень Java

Итоги

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

Давайте потренируемся!

Средний уровень Java

Preparing Video For Download...