This is a simple example of how Switch Case statements in Java work:
-----------------------------SwitchCase.java-----------------------------
import java.io.*;
import java.util.*;
public class SwitchCase {
public static void main(String [] args) throws IOException{
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
int x = 2;
switch(x){
case 1:
System.out.println("x is 1!");
break;
case 2:
System.out.println("x is 2!");
System.out.println("Hello!");
break;
case 3:
System.out.println("x is 3!");
break;
default:
System.out.println("x is invalid!");
break;
} // switch closes
}
}
-----------------------------end of SwitchCase.java-----------------------------
Problem: Create a program that would ask the user for the following options:
1: to add
2: to multiply
3: to deduct
Then ask the user for two numbers and display the answer based on the operation chosen.
----------------------Calc.java----------------------------
import java.io.*;
import java.util.*;
public class Calc {
public static void main(String [] args) throws IOException{
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
int option, first, second, answer;
System.out.print("1: to add \n2: to multiply \n3: to deduct \nEnter option: ");
option = Integer.parseInt(keyboard.readLine());
System.out.print("Enter first number: ");
first = Integer.parseInt(keyboard.readLine());
System.out.print("Enter second number: ");
second = Integer.parseInt(keyboard.readLine());
switch(option){
case 1: answer = first + second; break;
case 2: answer = first * second; break;
case 3: answer = first - second; break;
default: System.out.print("Invalid"); answer = 0; break;
}
System.out.println("Answer: " + answer);
}
}
----------------------end of Calc.java----------------------------
------------------------Options.java ----------------------------------
import java.io.*; import java.util.*;
public class Options {
public static void main(String [] args) throws IOException{
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
int option;
System.out.print("Enter option: ");
option = Integer.parseInt(keyboard.readLine());
switch(option){
case 1:
for(int i = 1; i <= 10; i++) { System.out.print(i + " ");}
break;
case 2:
int sum, no1, no2;
System.out.print("Enter first number: ");
no1 = Integer.parseInt(keyboard.readLine());
System.out.print("Enter second number: ");
no2 = Integer.parseInt(keyboard.readLine());
sum = no1 + no2;
System.out.print("The sum is " + sum);
break;
case 3:
int no, rem;
System.out.print("Enter number: ");
no = Integer.parseInt(keyboard.readLine());
rem = no % 2;
if(rem == 1) System.out.print("Odd.");
else System.out.print("Even");
break;
default:
System.out.print("Invalid option");
break;
}
}
}