switchcase

  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);
    }
    D
    switch_case.solution.1
  2. caseの値が異なることを利用して、次のように記述することもできる。
    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;
    }
    D
  3. defaultセクションは例外をスローするために必要なので、final switch文にはできなくなった。プログラムの変更部分は次の通りだ。
    // ...
    
        switch (op) {
    
        // ...
    
        default:
            throw new Exception("Invalid operation: " ~ op);
        }
    
    // ...
    D