If Statement
import java.util.*;
public class IfState{
public static void main(String args[]){
System.out.println("Enter a Number Between 1-5");
Scanner sc= new Scanner(System.in);
int num=sc.nextInt();
if (num==1){
System.out.println("You Entered One");
}
else if (num==2){
System.out.println("You Entered Two");
}
else if (num==3){
System.out.println("You Entered Three");
}
else if (num==4){
System.out.println("You Entered Four");
}
else if (num==5){
System.out.println("You Entered Five");
}
else {
System.out.println("Enter a Valid Number");
}
}
}
Output:
Switch Statement
import java.util.*;
public class Switch{
public static void main(String args[]){
System.out.println("Enter a Number Between 1-5");
Scanner sc= new Scanner(System.in);
int num=sc.nextInt();
switch (num){
case 1:
System.out.println("You Entered One");
break;
case 2:
System.out.println("You Entered Two");
break;
case 3:
System.out.println("You Entered Three");
break;
case 4:
System.out.println("You Entered Four");
break;
case 5:
System.out.println("You Entered Five");
break;
default:
System.out.println("Enter a Valid Number");
}
}
}
Output:
import java.util.*;
public class Switch{
public static void main(String args[]){
System.out.println("Enter a Number Between 1-5");
Scanner sc= new Scanner(System.in);
int num=sc.nextInt();
switch (num){
case 1:
System.out.println("You Entered One");
case 2:
System.out.println("You Entered Two");
case 3:
System.out.println("You Entered Three");
case 4:
System.out.println("You Entered Four");
case 5:
System.out.println("You Entered Five");
default:
System.out.println("Enter a Valid Number");
}
}
}
Output:
අපි break බාවිතා කරගෙන අදාල case එකක් execute උනාට පස්සේ program එක terminate කරේ නැත්තම් ඊටපස්සේ තියන හැම case එකක්ම execute වෙනවා. මෙතන default keyword එක if statement එකේ else ට සමානයි. මේ දීල තියන case වලට අදාළ නොවන input එකක් user enter කලොත් default යටතේ තියන code එක execute වෙනවා. Default සමග break බාවිතා කරන්න ඕනේ නැහැ.
ConversionConversion EmoticonEmoticon