Programming in D – Solutions

switch and case

  1. import std.stdio;
    import std.string;
    
    void main() {
        string op;
        double first;
        double second;
    
        write("Please enter the operation: ");
        op = strip(readln());
    
        write("Please enter two values separated by a space: ");
        readf(" %s %s", &first, &second);
    
        double result;
    
        final switch (op) {
    
        case "add":
            result = first + second;
            break;
    
        case "subtract":
            result = first - second;
            break;
    
        case "multiply":
            result = first * second;
            break;
    
        case "divide":
            result = first / second;
            break;
        }
    
        writeln(result);
    }
    
  2. By taking advantage of distinct case values:
        final switch (op) {
    
        case "add", "+":
            result = first + second;
            break;
    
        case "subtract", "-":
            result = first - second;
            break;
    
        case "multiply", "*":
            result = first * second;
            break;
    
        case "divide", "/":
            result = first / second;
            break;
        }
    
  3. Since the default section is needed to throw the exception from, it cannot be a final switch statement anymore. Here are the parts of the program that are modified:
    // ...
    
        switch (op) {
    
        // ...
    
        default:
            throw new Exception("Invalid operation: " ~ op);
        }
    
    // ...