How to use switch case statement in java with example, switch case statement is used when there are multiple condition in java
Syntax
switch(Variable){
case value:
code statement;
break;
case value:
code statement;
break;
default:
delault value not in above cases;
}
Example
Write a program which allows user to enter a integer from todays day, and user get to know which day of week it will be after certain days (consider today as sunday,0 for sunday )Today is day 0.
Program
import java.util.Scanner;// this package util and Class Scanner is declared to take input from user
/*
*@ scanner class
* @author khant vyas
*/
public class weekdays // name of class
{
public static void main(String args[])
{
int a,b;// a is variable to store summation of given numbers
System.out.println("Enter the number of days from today and will tell you which day will be after thpse days");
System.out.println("(consider today as sunday)");
Scanner sc = new Scanner(System.in);// sc is object to the Scanner class
a=sc.nextInt();// nextInt() method is used accept intiger value from user
b=a%7; // b stores value by dividing a by 7 to sort day
switch(b)
{
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
}
}
}
Output:
Syntax
switch(Variable){
case value:
code statement;
break;
case value:
code statement;
break;
default:
delault value not in above cases;
}
Example
Write a program which allows user to enter a integer from todays day, and user get to know which day of week it will be after certain days (consider today as sunday,0 for sunday )Today is day 0.
Program
import java.util.Scanner;// this package util and Class Scanner is declared to take input from user
/*
*@ scanner class
* @author khant vyas
*/
public class weekdays // name of class
{
public static void main(String args[])
{
int a,b;// a is variable to store summation of given numbers
System.out.println("Enter the number of days from today and will tell you which day will be after thpse days");
System.out.println("(consider today as sunday)");
Scanner sc = new Scanner(System.in);// sc is object to the Scanner class
a=sc.nextInt();// nextInt() method is used accept intiger value from user
b=a%7; // b stores value by dividing a by 7 to sort day
switch(b)
{
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
}
}
}
Output:
Switch case java |
No comments:
Post a Comment