8. ตัว อย่า ง โปรแกรมที่ใ ช้ค ำา สัง
่ if
public class SampleIf {
public class SampleIf {
public static void main(String args[]) {
public static void main(String args[]) {
int score = Integer.parseInt(args[0]);
int score = Integer.parseInt(args[0]);
if (score >= 50) {
if (score >= 50) {
System.out.println("You pass");
System.out.println("You pass");
}}
}}
}}
17. ตัว อย่า งโปรแกรมที่ใช้ค ำา สั่ง if..else
if..else
public class SampleIfElseIf {
public class SampleIfElseIf {
public static void main(String args[]) {
public static void main(String args[]) {
int x = Integer.parseInt(args[0]);
int x = Integer.parseInt(args[0]);
if (x == 1) {
if (x == 1) {
System.out.println("Value is one");
System.out.println("Value is one");
} else if (x == 2) {
} else if (x == 2) {
System.out.println("Value is two");
System.out.println("Value is two");
} else {
} else {
System.out.println("Other than 1 or 2");
System.out.println("Other than 1 or 2");
}}
}}
}}
18. รูป แบบของ คำา สัง
่ switch
มีร ูป แบบการใช้ค ำา สั่ง ดัง นี้
switch (expression) {
case value 1: statements 1
break;
case value 2: statements 2
break;
: :
case value N: statements N
break;
default: statements N+1;
}
21. ตัว อย่า งโปรแกรมที่ใช้ค ำา สั่ง switch
public class SampleSwitch {
public static void main(String args[]) {
int x = Integer.parseInt(args[0]);
switch(x) {
case 1: System.out.println("Value is one");
break;
case 2: System.out.println("Value is two");
break;
default: System.out.println("Other than 1 or 2");
}
}
}
28. ตัว อย่า งโปรแกรมที่ใช้ค ำา สั่ง
do..while
public class SampleDoWhile {
public class SampleDoWhile {
public static void main(String args[]) {
public static void main(String args[]) {
int i = 1;
int i = 1;
do {
do {
System.out.print(i+" ");
System.out.print(i+" ");
i++;
i++;
} while (i <= 10);
} while (i <= 10);
}}
}}
ผลลัพ ธ์ท ไ ด้จ ากการรัน โปรแกรม
ี่
1 2 3 4 5 6 7 8 9 10