0
public class ChineseZodiac
{
    public static void Main(String[] args)
    {
      
        Console.Write("Enter a year: "); 
        var year = Convert.ToInt64(Console.ReadLine());
        switch (year % 12) 
        {
            case 0:
                Console.WriteLine("monkey");
                break;
            case 1:
                Console.WriteLine("rooster");
                break;
            case 2:
                Console.WriteLine("dog");
                break;
            case 3:
                Console.WriteLine("pig");
                break;
            case 4:
                Console.WriteLine("rat");
                break;
            case 5:
                Console.WriteLine("ox");
                break;
            case 6:
                Console.WriteLine("tiger");
                break;
            case 7:
                Console.WriteLine("rabbit");
                break;
            case 8:
                Console.WriteLine("dragon");
                break;
            case 9:
                Console.WriteLine("snake");
                break;
            case 10:
                Console.WriteLine("horse");
                break;
            case 11:
                Console.WriteLine("sheep");
                break;
        }
    }
}

I'm trying to get the formula in the switch statement block to output a zodiac sign based on the user's input. I'm also supposed to have the switch statement converted to a switch expression with the same results. I was able to run it without any errors in VS Code as a switch statement but I'm confused about the difference between a switch statement and a switch expression.

2 Answers2

1

Switch expressions return a value, so you couldn't do exactly what you're doing now (since the action is happening within the switch), but you could use it to return the string and then display it:

var yearMod12 = year % 12;
var yearOf = yearMod12 switch 
{
    0 => "monkey",
    1 => "rooster",
    ...
};
Console.WriteLine(yearOf);

An enum or Dictionary<int, string> would be a good choice for this type of mapping as well.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

I suggest extracting model (animals) into a collection; try keeping data and actions separatedly:

public class ChineseZodiac { 
  // Model (data): Zodiac animals
  private static readonly IReadOnly<string> s_Animals = new string[] {
    "monkey", "rooster", "dog", 
    "pig", "rat", "ox",
    "tiger", "rabbit", "dragon",
    "snake", "horse", "sheep",
  };

  // An action which is based on the model
  public static void Main(String[] args) {
    Console.Write("Enter a year: "); 
    
    Console.WriteLine(s_Animals[int.Parse(Console.ReadLine()) % s_Animals.Count]); 
  }
} 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215