mathajax

Java program Arithmetic calculator - switch case string

The javacode a simple arithmetic calculator using switch case with string constant.

On executing the code, the used has to enter command and operands to do arithmetic operation. The command represented by string constant in switch-case specify which arithmetic operation is to do and The operands are integers on which the selected arithmetic operation is done.

  for example of addition operation, a command add and followed by two integer.
  "add 10 20".

  for subtraction
  "sub 10 20".

 and for multiplication
  "mul 10 20".



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SwitchCase 
  {

public static void main(String[] args) throws IOException  
{
    
 InputStreamReader dis =new InputStreamReader ( System.in );
 BufferedReader br =new BufferedReader(dis);
 int ans=0;
         
    System.out.println("Enter cmd & operand ");            
    String  arg = br.readLine();
    String cmdopr[]= arg.split(" ");
        
 switch(cmdopr[0]) 
    {
    
    case "add" :
  ans=Integer.parseInt(cmdopr[1]) + Integer.parseInt(cmdopr[2]);
  System.out.println("ans :"+ans);
         break;

    case "sub" :
  ans=Integer.parseInt(cmdopr[1]) - Integer.parseInt(cmdopr[2]);
  System.out.println("ans :"+ans);
  break;

    case "mul" :
   ans=Integer.parseInt(cmdopr[1]) * Integer.parseInt(cmdopr[2]);
   System.out.println("ans :"+ans);
   break;

    case "div":
          ans=Integer.parseInt(cmdopr[1]) / Integer.parseInt(cmdopr[2]);
          System.out.println("ans :"+ans);
   break;

     default : 
  System.out.println(arg + ":command not executable");
      }                 

  }

}


Output
Enter cmd & operand 
add 12 15
ans :27

Enter cmd & operand 
mul 5 6
ans :30





Comments

Popular posts from this blog

Solving System of Linear Equations by Gauss Jordan Elimination

Matrix Forward and Back Substitution

Solve System of Linear Equations by LU Decompose

Chebyshev distance between two points

Binary 1's and 2's Complement