我是c#的新手,我用多个对象构建了一个心理健康项目--从循环开始。是否有更巧妙的方法来处理这些代码?我通过以下方式运行基本代码输入:
Console.WriteLine("How are you feeling (1-bad to 5 great)?");
var userInput = Console.ReadLine();
Console.WriteLine(" Mood: " + userInput);        
if (! Int32.TryParse(userInput, out x))
{
   Console.WriteLine("Invalid data input");
}
else if (x == 1)
{
   Console.WriteLine(" very low.");    
}
else if (x == 2)
{
   Console.WriteLine(" low.");
}
else if (x == 3)
{
   Console.WriteLine(" average.");
}
else if (x == 4)
{
   Console.WriteLine(" good.");
}
else if (x == 5)
{
   Console.WriteLine(" very good.");
}发布于 2022-01-18 00:44:20
试试这个,它的代码更紧凑。
    var invalidData = false;
    var x = 0;
    var moods = new string[] { " very low.", " low.", " average.", " good.", " very good." };
    do
    {
        Console.WriteLine("How are you feeling(1 - bad to 5 great)?");
        var userInput = Console.ReadLine();
        Console.WriteLine(" Mood: " + userInput);
        if (!Int32.TryParse(userInput, out x) || x < 1 || x > 5)
        {
            Console.WriteLine("Invalid data input");
            invalidData = true;
        }
        else invalidData = false;
    }
    while (invalidData);
    Console.WriteLine(moods[x-1]);https://stackoverflow.com/questions/70749034
复制相似问题