switch statement in while loop java code example
Example 1: switch statement in java
// switch case in java example programs
public class SwitchStatementExample
{
public static void main(String[] args)
{
char grade = 'A';
switch(grade) {
case 'A' :
System.out.println("Distinction.");
break;
case 'B' :
case 'C' :
System.out.println("First class.");
break;
case 'D' :
System.out.println("You have passed.");
case 'F' :
System.out.println("Fail. Try again.");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Grade is: " + grade);
}
}
Example 2: switch statement in java
// syntax of switch statement in java
switch(expression)
{
case 1 value :
// code goes here
break;
case 2 value :
// code goes here
break;
case 3 value :
// code goes here
break;
.
.
.
.
default: // optional
// default code goes here
}
Example 3: switch statement in while loop java
Scanner input=new Scanner(System.in);
int selection = input.nextInt();
while (selection<4)
{
switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
selection = input.nextInt(); // add this
}