Thursday, August 25, 2016

Java Calculator Assignment



import java.util.Scanner;

public class Calc {

    enum Op {

        ADD("a", "add", "+"),
        SUB("s", "subtract", "-"),
        MUL("m", "multiply", "*"),
        DIV("d", "divide", "/"),
REM("r", "to get reminder" ,"%" );
        public String key;
        public String command;
        public String result;

        Op(String key, String command, String result) {
            this.key = key;
            this.command = command;
            this.result = result;
        }

        public double eval(double x, double y) {
            switch (this) {
                case ADD:
                    return x + y;
                case SUB:
                    return x - y;
                case MUL:
                    return x * y;
                case DIV:
                    return x / y;
case REM:
return x % y;
                default:
                    throw new AssertionError();
            }
        }
    }

    public static void main(String[] args) {
        while (true) //creates loop to top
        {
            System.out.println("Welcome to Java calculator!");
            System.out.println("To add(+)            type 'a'");
            System.out.println("To subtract(-)       type 's'");
System.out.println("To multiply(*)       type 'm'");
System.out.println("To divide(/)         type 'd'");
System.out.println("To get reminder(%)   type 'r'");
            Scanner scan = new Scanner(System.in);    //sets up scanners
            Scanner scan1 = new Scanner(System.in);


            String action = scan.nextLine();

            Op op = null;
            for (Op operation : Op.values()) {
                if (operation.key.equals(action)) {
                    op = operation;
                    break;
                }
            }

            if (op != null) {
                System.out.println("Enter the first number you would like to " + op.command + ".");
                double x = scan.nextInt();
                System.out.println("Now enter the second number.");
                double y = scan.nextInt();
                double z = op.eval(x, y);
                System.out.println(x + " " + op.result + " " + y + " = " + z + "//");
            }

            System.out.println("Would you like to start over? (yes,no)");
            String startOver = scan1.nextLine();

            if ("no".equals(startOver)) {
System.out.println(".......Bye.....");
                return;
            }
        }
    }
}

No comments:

Post a Comment