SWITCH STATEMENT IN JAVA
Switch statement is also used to implement two and more than two logical conditions like Else if statement.
In switch statement we use 'case' to implement the logical conditions.
SYNTAX FOR SWITCH STATEMENT
switch(switch_variable)
{
case 1:
statement ...
break;
case 2:
statement ...
break;
default:
.........
}
import java.util.Scanner; // Import the Scanner class
class Result
{
public static void main(String[] args)
{
int a,b,c,r=0;
System.out.print("Enter first number: ");
// Method to accept input from user at run time
Scanner in = new Scanner(System.in);
a=in.nextInt();
System.out.print("Enter second number: ");
b=in.nextInt();
System.out.println("1. Add \t 2. Sub\n");
System.out.println("3. Mul \t 4. Div");
System.out.print("\nEnter your choice (1-4): ");
c=in.nextInt();
switch(c)
{
case 1:
r=a+b; break;
case 2:
r=a-b; break;
case 3:
r=a*b; break;
case 4:
r=a/b; break;
}
System.out.println("Result is: "+r);
}
}
- - - PROGRAM OUTPUT - - -
Example 2: Program to generate shopping bill.
import java.util.Scanner; // Import the Scanner class
class Shopping
{
public static void main(String[] args)
{
int c, q, b=0;
System.out.println("* * * Welcome in Amit General Store * * *\n");
System.out.println("1. Tea Rs. 10 \t 2. Samosa Rs. 12\n");
System.out.println("3. Cold drink Rs. 40 \t 4. Coffee Rs. 25");
System.out.print("\nEnter your choice (1-4): ");
// Method to accept input from user at run time
Scanner in = new Scanner(System.in);
c=in.nextInt();
System.out.print("Enter the quantity: ");
q=in.nextInt();
switch(c)
{
case 1:
b=q*10; break;
case 2:
b=q*12; break;
case 3:
b=q*40; break;
case 4:
b=q*25; break;
default:
System.out.println("Wrong choice");
}
System.out.println("Total bill amount is: "+b);
}
}
class Shopping
{
public static void main(String[] args)
{
int c, q, b=0;
System.out.println("* * * Welcome in Amit General Store * * *\n");
System.out.println("1. Tea Rs. 10 \t 2. Samosa Rs. 12\n");
System.out.println("3. Cold drink Rs. 40 \t 4. Coffee Rs. 25");
System.out.print("\nEnter your choice (1-4): ");
// Method to accept input from user at run time
Scanner in = new Scanner(System.in);
c=in.nextInt();
System.out.print("Enter the quantity: ");
q=in.nextInt();
switch(c)
{
case 1:
b=q*10; break;
case 2:
b=q*12; break;
case 3:
b=q*40; break;
case 4:
b=q*25; break;
default:
System.out.println("Wrong choice");
}
System.out.println("Total bill amount is: "+b);
}
}
- - - PROGRAM OUTPUT - - -
0 Comments