📜  Dart编程 – If Else 语句(if , if..else, Nested if, if-else-if)

📅  最后修改于: 2021-09-02 05:32:57             🧑  作者: Mango

决策语句是那些允许程序员决定哪个语句应该在不同条件下运行的语句。有四种方法可以实现这一点:

如果声明:

这种类型的语句只是检查条件,如果它为真,则执行其中的语句,但如果不是,则在代码中简单地忽略这些语句。

Syntax: 
if ( condition ){
  // body of if
}

例子:

Dart
void main()
{
    int gfg = 10;
  
    // Condition is true
    if (gfg > 3) { 
      // This will be printed
        print("Condition is true"); 
    }
}


Dart
void main()
{
    int gfg = 10;
  
    // Condition is false
    if (gfg > 30) { 
      // This will not be printed
        print("Condition is true"); 
    }
    else {
      // This will be printed
        print("Condition id false"); 
    }
}


Dart
void main()
{
    int gfg = 10;
    if (gfg < 9) {
        print("Condition 1 is true");
        gfg++;
    }
    else if (gfg < 10) {
        print("Condition 2 is true");
    }
    else if (gfg >= 10) {
        print("Condition 3 is true");
    }
    else if (++gfg > 11) {
        print("Condition 4 is true");
    }
    else {
        print("All the conditions are false");
    }
}


Dart
void main()
{
    int gfg = 10;
    if (gfg > 9) {
        gfg++;
        if (gfg < 10) {
            print("Condition 2 is true");
        }
        else {
            print("All the conditions are false");
        }
    }
}


输出:

Condition is true

if…else 语句:

这种类型的语句只是检查条件,如果它为真,则执行其中的语句,但如果不是,则执行 else 语句。

Syntax: 
if ( condition ){
  // body of if
}
else {
  // body of else
}

例子:

Dart

void main()
{
    int gfg = 10;
  
    // Condition is false
    if (gfg > 30) { 
      // This will not be printed
        print("Condition is true"); 
    }
    else {
      // This will be printed
        print("Condition id false"); 
    }
}

输出:

Condition is false

否则……如果梯子:

这种类型的语句简单地检查条件,如果它为真,则执行其中的语句,但如果它不是,则检查其他条件,如果它们为真,则执行它们,如果不是,则检查另一个 if 条件.这个过程一直持续到梯子完成。

Syntax: 
if ( condition1 ){
  // body of if
}
else if ( condition2 ){
  // body of if
}
.
.
.
else {
  // statement
}

例子:

Dart

void main()
{
    int gfg = 10;
    if (gfg < 9) {
        print("Condition 1 is true");
        gfg++;
    }
    else if (gfg < 10) {
        print("Condition 2 is true");
    }
    else if (gfg >= 10) {
        print("Condition 3 is true");
    }
    else if (++gfg > 11) {
        print("Condition 4 is true");
    }
    else {
        print("All the conditions are false");
    }
}

输出:

Condition 3 is true

嵌套 if 语句:

这种类型的语句检查条件,如果为真,则其中的 if 语句检查其条件,如果为真,则执行语句,否则执行 else 语句。

Syntax: 
if ( condition1 ){
  if ( condition2 ){
     // Body of if
  }
  else {
    // Body of else
  }
}

例子:

Dart

void main()
{
    int gfg = 10;
    if (gfg > 9) {
        gfg++;
        if (gfg < 10) {
            print("Condition 2 is true");
        }
        else {
            print("All the conditions are false");
        }
    }
}

输出:

All the conditions are false