如何在具有字符串整数的循环中正确使用Console.Readline()



我是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.");
}

试试这个,它是更紧凑的代码

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]);

相关内容

  • 没有找到相关文章

最新更新