Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen else-if Statement in Dart | Conditional Statements
Introduction to Dart

book
else-if Statement in Dart

The else…if statement is useful to test multiple conditions. Following is the syntax of the same.

  • An if construct can contain any number of else if blocks of code;
  • It is not necessary to use the code block else.

Syntax

javascript
if (boolean_expression1) {
// statements if the expression1 evaluates to `true`
}
else if (boolean_expression2) {
// statements if the expression2 evaluates to `true`
}
else {
/* statements if both expression1
and expression2 result to `false` */
}

The else if syntax is like the if syntax:

else if keyword, value in the parentheses () and a code block in the curly brackets {}.

If one of the conditions is met, then after executing its code block, the subsequent conditions will not be checked, and the code blocks of those conditions will not be executed either.

Example

dart

main

copy
void main() {
int num = 2;
if(num > 0) {
print("is positive");
}
else if(num < 0) {
print("is negative");
}
else {
print("is zero");
}
}
123456789101112
void main() { int num = 2; if(num > 0) { print("is positive"); } else if(num < 0) { print("is negative"); } else { print("is zero"); } }

In this program, we have a variable num which is equal to 2. We use a conditional statement if to check if num is greater than 0. If this condition is true (meaning num is a positive number), it prints the message "is positive". Otherwise, if num is less than 0, it prints "is negative". If none of these conditions is true (i.e., num is equal to 0), it prints "is zero".

Task

Fix the code so that the program works correctly.

dart

main

copy
void main() {
var score = '2.0';
if( score is int ){
print('Type: int');
} ___ (___){
print('Type: double');
} else {
print('Type: other type');
}
}
12345678910
void main() { var score = '2.0'; if( score is int ){ print('Type: int'); } ___ (___){ print('Type: double'); } else { print('Type: other type'); } }

else if (score is double) - correct condition

dart

main

copy
void main() {
var score = '2.0';
if( score is int ){
print('Type: int');
} else if (score is double){
print('Type: double');
} else {
print('Type: other type');
}
}
12345678910
void main() { var score = '2.0'; if( score is int ){ print('Type: int'); } else if (score is double){ print('Type: double'); } else { print('Type: other type'); } }

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 3
some-alt