Arrays: Calculator

Question: Write a program that takes three arguments (num1 operation num2) from the command line and displays the result of the expression

package Array;

/**
 * Created by aarushi on 7/5/21.
 */
public class ArrayCalculator {

    public static void main (String [] args){
        //Initialise the variable where the result will be stored
        Integer result= null;

        //check validity of entered values
        if (args.length!=3){
            System.out.println("Values entered are incorrect");
            System.exit(1);
        }

        //deal with each operation
        //Since elements of the args array are all strings we have to convert
        //them to integer values to carry arithmetic operations on them
        switch(args[1].charAt(0)){
            case '+':
                result= Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
                break;
            case '-':
                result= Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
                break;
            case '*':
                result= Integer.parseInt(args[0])* Integer.parseInt(args[2]);
                break;
            case '/':
                result= Integer.parseInt(args[0])/ Integer.parseInt(args[2]);
                break;
            default:
                System.out.println("Invalid operation");
        }

        System.out.println("The result is " + result);
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.