|
รูปแบบ มีดังนี้ |
| |
|
if (เงื่อนไขที่ต้องการตรวจสอบ)
|
|
{คำสั่งที่ 1
เมื่อตรงตามเงื่อนไข} |
|
{คำสั่งที่ 2
เมื่อไม่ตรงตามเงื่อนไข} |
|
|
public class
Testif
{ public static void main(String args [ ])
{
int x=5;
if (x==5)
{System.out.println("x = 5");}
else
{System.out.println("x != 5");}
}
} |
|
ผลการ Run |
|
 |
|
Nested if
แบบที่ 1
if (เงื่อนไข1)
{ if (เงื่อนไข2)
{ if (เงื่อนไข3)
}
}
else
{ คำสั่งต่าง ๆ เมื่อเงื่อนไขเป็นเท็จ; }
แบบที่ 2
if (เงื่อนไข1) { คำสั่งเมื่อเงื่อนไข1 เป็นจริง; }
else
if (เงื่อนไข2) { คำสั่งเมื่อเงื่อนไข2 เป็นจริง; }
else
if (เงื่อนไข3) { คำสั่งเมื่อเงื่อนไข3 เป็นจริง; }
|
public class
Testif
{ public static void main(String args [ ])
{
int x=6;
if (x==5)
{System.out.println("x = 5");}
else
{System.out.println("x != 5");}
}
} |
|
ผลการ Run |
|
 |
|
|
public class
Testif
{ public static void main(String args [ ])
{
int x=6;
if (x==5)
{System.out.println("x = 5");}
else if (x==6)
{System.out.println("x = 6");}
else
{System.out.println("x != 5 and 6");}
}
} |
|
ผลการ Run |
|
 |
|
|
public class
Testif
{ public static void main(String args [ ])
{
int x=7;
if (x==5)
{System.out.println("x = 5");}
else if (x==6)
{System.out.println("x = 6");}
else
{System.out.println("x != 5 and 6");}
}
} |
|
ผลการ Run |
|
 |
|
|
public class
Testif
{ public static void main(String args [ ])
{
int x=6;
if ( x == 5 || x == 6 )
{System.out.println("x = 5 and 6");}
else
{System.out.println("x != 5 and 6");}
}
} |
|
ผลการ Run |
|
 |
|
| |