我想添加开关盒,以免用户在输入温度或没有什么要删除的情况下写字符串,它说“没有什么要删除,请返回菜单”。
List<string> Temp = new List<string>();
while (true)
{
string val;
Console.WriteLine("[L] ägg till temp-mätning: ");
Console.WriteLine("[S] kriv ut alla temperaturer och medeltemperatur");
Console.WriteLine("[T] ag bort temp-mätning");
Console.WriteLine("[A] vsluta");
Console.Write("Selection: ");
val = Console.ReadLine();
if (val == "l" || val == "L")
{
Console.WriteLine("add temperature : ");
Temp.Add(Console.ReadLine());
Console.Clear();
}
else if(val == "s" || val == "S")
{
int index = 1;
Console.Clear();
Console.WriteLine($"Your temperatures are: ");
Temp.ForEach(x => Console.WriteLine($"{index++} - {x}"));
}
else if (val == "t" || val == "T")
{
Console.Write($"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
int deleteIndex = int.Parse(Console.ReadLine()) - 1;
Temp.RemoveAt(deleteIndex);
}
else
{
Console.WriteLine("incorrect input: ");
Console.Clear();
break;
}
问问题之前,请使用C#参考网站或书籍。
由于您仅捕获单个字符,因此可以考虑使用Console.ReadKey()
而不是Console.ReadLine()
,然后可以与按下的ConsoleKey
键而不是输入的字符进行比较。并且由于我们实际上不需要存储输入的值,因此我们可以直接在switch语句中使用它,例如:switch (Console.ReadKey().Key)
例如:
while (true)
{
Console.WriteLine("[L] ägg till temp-mätning: ");
Console.WriteLine("[S] kriv ut alla temperaturer och medeltemperatur");
Console.WriteLine("[T] ag bort temp-mätning");
Console.WriteLine("[A] vsluta");
Console.Write("Selection: ");
switch (Console.ReadKey().Key)
{
case ConsoleKey.L:
Console.WriteLine("add temperature : ");
Temp.Add(Console.ReadLine());
Console.Clear();
break;
case ConsoleKey.S:
int index = 1;
Console.Clear();
Console.WriteLine($"Your temperatures are: ");
Temp.ForEach(x => Console.WriteLine($"{index++} - {x}"));
break;
case ConsoleKey.T:
Console.Write($"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
int deleteIndex = int.Parse(Console.ReadLine()) - 1;
Temp.RemoveAt(deleteIndex);
break;
default:
Console.WriteLine("incorrect input: ");
Console.Clear();
break;
}
}