練習 - 完成使用 switch 陳述式的挑戰活動

已完成

程式代碼挑戰將強化您已學到的內容,並協助您在繼續之前獲得一些信心。

切換為 switch 語句挑戰

在此挑戰中,您將把if-elseif-else結構重寫成switch語句。 與 switch 結構相較,此挑戰可協助您了解 if-elseif-else 陳述式的優劣。 祝你好運。

程式碼挑戰:使用 switch 語句重寫 if-elseif-else

您將從使用 if-elseif-else 建構來評估產品 SKU 元件的程式代碼開始。 SKU(庫存單位)會使用三個編碼值來格式化: <product #>-<2-letter color code>-<size code>。 例如,的 SKU 值 01-MN-L 會對應至 (汗衫)-(馬龍)-(大型),而程式代碼會輸出顯示為「產品:大馬龍汗衫」的描述。

您的挑戰是將 if 語句程式代碼轉換成與初始程式代碼 switch 相同的結果的語句。

  1. 請確定您已在 Visual Studio Code 中開啟空的 Program.cs 檔案。

    如有必要,請開啟 Visual Studio Code,然後完成下列步驟,以在編輯器中備妥 Program.cs 檔案:

    1. 在 [檔案] 功能表上,選取 [開啟資料夾]

    2. 使用 [開啟資料夾] 對話框瀏覽至 CsharpProjects 資料夾,然後開啟。

    3. 在 Visual Studio Code 的 [總管] 窗格中,選取 [Program.cs]

    4. 在 Visual Studio Code [選取項目] 功能表上,選取 [全部選取],然後按 [刪除] 鍵。

  2. 在 [Visual Studio Code 編輯器] 中輸入下列程式碼:

    // SKU = Stock Keeping Unit. 
    // SKU value format: <product #>-<2-letter color code>-<size code>
    string sku = "01-MN-L";
    
    string[] product = sku.Split('-');
    
    string type = "";
    string color = "";
    string size = "";
    
    if (product[0] == "01")
    {
        type = "Sweat shirt";
    } else if (product[0] == "02")
    {
        type = "T-Shirt";
    } else if (product[0] == "03")
    {
        type = "Sweat pants";
    }
    else
    {
        type = "Other";
    }
    
    if (product[1] == "BL")
    {
        color = "Black";
    } else if (product[1] == "MN")
    {
        color = "Maroon";
    } else
    {
        color = "White";
    }
    
    if (product[2] == "S")
    {
        size = "Small";
    } else if (product[2] == "M")
    {
        size = "Medium";
    } else if (product[2] == "L")
    {
        size = "Large";
    } else
    {
        size = "One Size Fits All";
    }
    
    Console.WriteLine($"Product: {size} {color} {type}");
    
  3. 更新程式代碼以使用 switch 語句取代 if-elseif-else 建構。

  4. 確認您的輸出尚未變更。

    無論您如何執行,您的程式代碼都應該產生下列輸出:

    Product: Large Maroon Sweat shirt
    

無論您是停滯不前,需要查看解決方案,還是您順利完成,請繼續檢視此挑戰的解決方案。