Application : Calculator (For 3 Numbers)

Requirements:
Create Calculator Application to have following functionality,
- Add 3 numbers
- Subtract 3 numbers
- Divide 3 numbers 
- Multiply 3 numbers


- Take command line input for 3 numbers
- User can enter option based on the menu as shown below,

Menu 
(1=Add, 2=Sub, 3=Div, 4=Mul )


Design:

Implementation:
[CalculatorApp.java]
import java.util.Scanner;

public class CalculatorApp {

    public static void main(String[] args) {



        //read command line arguments from the command line while running this application
        double n1 = Double.parseDouble(args[0]);  //first number
        double n2 = Double.parseDouble(args[1]);  //second number
        double n3 = Double.parseDouble(args[2]);  //third number
        

        //use to get user input for operation
        Scanner scan = new Scanner(System.in);

    
        System.out.println("Menu ");
        System.out.println("(1=Add, 2=Sub, 3=Div, 4=Mul )");

        int option = scan.nextInt();
   
        CalculatorApp appC = new CalculatorApp();

        switch (option) {

        case 1 :
            appC.add(n1, n2, n3);
            break;

        case 2 :
            appC.sub(n1, n2, n3);
            break;

        case 3 :
            appC.div(n1, n2, n3);
            break;
        case 4 :
            appC.mul(n1, n2, n3);
            break;

        default :
            System.out.println("Invalid option.");
        }
   
    } //end of main() method

    //Method to add three numbers and display results
    public void add(double n1, double n2, double n3) {
        System.out.println("Adding...");
        double result = n1 + n2 + n3;
        System.out.println(result);
    }

    
 //Method to subtract three numbers and display results    

    public void sub(double n1, double n2, double n3) {
        System.out.println("Subtracting...");
        double result = n1 - n2 - n3;
        System.out.println(result);
    }

    //Method to divide three numbers and display results  
    public void div(double n1, double n2, double n3) {
        System.out.println("Dividing...");
        double result = n1 / n2 / n3;
        System.out.println(result);
    }

   //Method to multiply three numbers and display results  
    public void mul(double n1, double n2, double n3) {
        System.out.println("Multiplying...");
        double result = n1 * n2 * n3;
        System.out.println(result);
    }

}



Testing:
=============How to Compile using java command line without Eclipse
javac CalculatorApp.java
The above command will compile CalculatorApp.java to CalculatorApp.class
=============How to Run using Command prompt (such as dos/unix/linux) 
java CalculatorApp 1 2 3
The above command will run CalculatorApp application with 3 arguments (Number1, Number2 and Number3)
=============Output: For Add option [other 3 options (Sub, Div, Mul) ]
Menu 
(1=Add, 2=Sub, 3=Div, 4=Mul )


1
Adding...
6.0

No comments :

Post a Comment