Switch statement is an alternative statement for the election statement. Usually
class DemoSwitch1 {
public static void main(String[] args) {
int noHari = 4;
switch (noHari) {
case 1:
System.out.println("Hari ke-" + noHari + " adalah Minggu");
break;
case 2:
System.out.println("Hari ke-" + noHari + " adalah Senin");
break;
case 3:
System.out.println("Hari ke-" + noHari + " adalah Selasa");
break;
case 4:
System.out.println("Hari ke-" + noHari + " adalah Rabu");
break;
case 5:
System.out.println("Hari ke-" + noHari + " adalah Kamis");
break;
case 6:
System.out.println("Hari ke-" + noHari + " adalah Jum\'at");
break;
case 7:
System.out.println("Hari ke-" + noHari + " adalah Sabtu");
break;
default:
System.out.println("Tidak ada hari ke-" + noHari);
}
}
used to simplify the complexity of many if statement
containing conditions. The general form of writing is:
Switch (expression) {
case value1:
/ / statement which will be made if the same expression value1
break;
case value2:
/ / statement that will be done if the expression equal to value2
break;
...
nilaiN case:
/ / statement which will be made if the same expression nilaiN
break;
default:
/ / statement which will be made if all values
defined above do not have the same expression
}
Sample program Java
containing conditions. The general form of writing is:
Switch (expression) {
case value1:
/ / statement which will be made if the same expression value1
break;
case value2:
/ / statement that will be done if the expression equal to value2
break;
...
nilaiN case:
/ / statement which will be made if the same expression nilaiN
break;
default:
/ / statement which will be made if all values
defined above do not have the same expression
}
Sample program Java
public static void main(String[] args) {
int noHari = 4;
switch (noHari) {
case 1:
System.out.println("Hari ke-" + noHari + " adalah Minggu");
break;
case 2:
System.out.println("Hari ke-" + noHari + " adalah Senin");
break;
case 3:
System.out.println("Hari ke-" + noHari + " adalah Selasa");
break;
case 4:
System.out.println("Hari ke-" + noHari + " adalah Rabu");
break;
case 5:
System.out.println("Hari ke-" + noHari + " adalah Kamis");
break;
case 6:
System.out.println("Hari ke-" + noHari + " adalah Jum\'at");
break;
case 7:
System.out.println("Hari ke-" + noHari + " adalah Sabtu");
break;
default:
System.out.println("Tidak ada hari ke-" + noHari);
}
}
No comments:
Post a Comment