How i can use the string in switch case as an action?

I'm trying to code a Calculator on Java but in the switch statement, it takes the operation as a String, how can I transform it into an action?

switch(op) {
    case 1: operation = "res= a + b";
    break;
    case 2: operation = "res = a - b";
    break;
    case 3: operation = "res = a * b";
    break;
    case 4: operation = "res = a / b";
    break;
}
  
System.out.println(operation);

If I remove the quotes it says that I haven't initialized the variables. They are asked after choosing the operation.


Solution 1:

Don't perform the operation until you have the arguments:

import static java.lang.Integer.*;
import java.util.*;

class t1 {
    static void calc(Scanner in) {

        System.out.print("Operation: ");
        int op = in.nextInt();
        System.out.print("a: ");
        int a = in.nextInt();
        System.out.print("b: ");
        int b = in.nextInt();

        int res = 0;

        switch(op) {
            case 1:
                res = a + b;
                break;
            case 2:
                res = a - b;
                break;
            case 3:
                res = a * b;
                break;
            case 4:
                res = a / b;
                break;
            default:
                System.out.println("Invalid operation");
                System.exit(-1);
        }

        System.out.println(res);
    }

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        while (true) {
            calc(in);
        }
    }
}

You could verify the operation before asking for the operands, with an additional switch statement.

There are ways to set the operation before obtaining the operands, but it's best to learn to walk before you run.