确保用户输入在多个输入上是双倍的



在c#, Console中,我提示用户输入输入,我要确保这些输入是双精度的,如果不是,则会提示用户重新输入值。

下面是我的代码:

public static void userExpenses() {
Console.Write("Enter your Monthly Income (before deductions): ");
Program.Income = double.Parse(Console.ReadLine());
Console.Write("Enter your estimated monthly tax: ");
Program.Deductions[0] = Int32.Parse(Console.ReadLine());
Console.Write("Enter monthly expenses for 1. Groceries: ");
Program.Deductions[1] = Int32.Parse(Console.ReadLine());
Console.Write("Enter monthly expenses for 2. Water + Lights: ");
Program.Deductions[2] = Int32.Parse(Console.ReadLine());
Console.Write("Enter monthly expenses for 3. Transportation: ");
Program.Deductions[3] = Int32.Parse(Console.ReadLine());
Console.Write("Enter monthly expenses for 4. Phone/s: ");
Program.Deductions[4] = Int32.Parse(Console.ReadLine());
Console.Write("Enter monthly expenses for 5. Other: ");
Program.Deductions[5] = Int32.Parse(Console.ReadLine());
}

有办法做到这一点吗?

你可以这样写:

public static decimal GetValueFromUser(string query)
{
Console.Write(query);
while(!decimal.TryParse(Console.ReadLine(), out decimal result))
{
Console.Write("Error: Input was not a number. Try again:")
}
return result;
}

用法:

Program.Income = GetValueFromUser("Enter your Monthly Income (before deductions): ");

Mind:我使用decimal是因为浮点类型在处理金钱时非常糟糕。不过,您可以选择使用doubleint。他们也有TryParse方法。

相关内容

最新更新