C#中的浮点/双精度类型输入验证

3

这是我写的第一个程序(从上周一开始学习);我是一个彻底的新手。

我的问题是,当程序提示用户输入华氏度或摄氏度时(期望得到数字),如何防止输入无效字符时抛出异常?例如,当用户输入“asfasd”时,程序会抛出异常。

在发布此问题之前,我在网站上进行了很多搜索,并成功找到其他输入验证问题。然而,它们都涉及C和C++,由于我是一个新手,我很难理解这些语言与C#的关系。谢谢。请参见代码:

using System;


namespace Converter
{
class Program
{
    static void Main()
    {
        float? FahrenheitInput = null;
        double? CelsiusInput = null;
        float? KilogramInput = null;
        float? PoundsInput = null;
        int UserChoice = 0;
        do
        {

            Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
            Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
            UserChoice = int.Parse(Console.ReadLine());
            switch (UserChoice)
            {
                case 1:
                    Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
                    FahrenheitInput = float.Parse(Console.ReadLine());
                    Console.Clear();
                    Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
                    break;
                case 2:
                    Console.WriteLine("Enter the temperature in Celsius, number only:");
                    CelsiusInput = double.Parse(Console.ReadLine());
                    Console.Clear();
                    Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
                    break;
                case 5:
                    break;
                default:
                    Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
                    break;

            }
        } while (UserChoice != 5);


    }
    public static float? FahrenheitToCelsius(float? INPUT)
    {
        return (INPUT - 32) * 5 / 9;
    }
    public static double? CelsiusToFahrenheit(double? INPUT)
    {
        return INPUT * 1.8 + 32;
    }
}

}


你正在寻找一个 try catch https://msdn.microsoft.com/library/0yd65esw.aspx 或者一个正则表达式,但是当你本周开始阅读 try catch 文章时。 - FoldFence
5个回答

4

TryParse 在这里是你的好朋友。在大多数情况下,你应该优先使用 TryParse 而不是 Parse。在你的例子中,你可以这样做:

int validInt;
int.TryParse(Console.ReadLine(), out validInt);

float validFloat;
float.TryParse(Console.ReadLine(), out validFloat);

Parse vs. TryParse


4
你可以将其放在Try-Catch块中,也可以使用while循环来验证用户输入。
以下是带有while循环的代码,用于验证用户输入。
class Program
{
    static void Main(string[] args)
    {
        double FahrenheitInput = 0;
        double CelsiusInput = 0;
        double KilogramInput = 0;
        double PoundsInput = 0;
        int UserChoice = 0;
        do
        {

            Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
            Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
            UserChoice = int.Parse(Console.ReadLine());
            switch (UserChoice)
            {
                case 1:
                    Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
                    while (!double.TryParse(Console.ReadLine(), out FahrenheitInput))
                    {
                        Console.WriteLine("Invalid format, please input again!");
                    };
                    Console.Clear();
                    Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
                    break;
                case 2:
                    Console.WriteLine("Enter the temperature in Celsius, number only:");
                    while (!double.TryParse(Console.ReadLine(), out CelsiusInput))
                    {
                        Console.WriteLine("Invalid format, please input again!");
                    };
                    Console.Clear();
                    Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
                    break;
                case 5:
                    break;
                default:
                    Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
                    break;

            }
        } while (UserChoice != 5);

    }
    public static double FahrenheitToCelsius(double INPUT)
    {
        return (INPUT - 32) * 5 / 9;
    }
    public static double CelsiusToFahrenheit(double INPUT)
    {
        return INPUT * 1.8 + 32;
    }
}

2

在我看来,改变例行程序最简单的方法是将Parse重写为相应的TryParse

  // UserChoice = int.Parse(Console.ReadLine());
  UserChoice = int.TryParse(Console.ReadLine(), out UserChoice) ? UserChoice : -1;

稍微复杂一些(您需要将float转换为float?

  // FahrenheitInput = float.Parse(Console.ReadLine());
  float v;
  FahrenheitInput = float.TryParse(Console.ReadLine(), out v) ? (float?) v : null;

相同方案适用于 CelsiusInput
  // CelsiusInput = double.Parse(Console.ReadLine());
  double d;
  CelsiusInput = double.TryParse(Console.ReadLine(), out v) d (double?) d : null;

代码的基本机制是

  • 我们尝试解析用户输入 TryParse(Console.ReadLine()...
  • 如果解析成功(因此TryParse返回true),我们只需返回输出值(已解析的值)。
  • 如果解析失败(因此TryParse返回false),我们将返回一些特殊值(对于UserChoice-1,对于FahrenheitInputCelsiusInput则为null

P.S. 在第一个switch中,您只有case 1case 2case 5;然而,在错误消息中,您放置了"This is not a valid entry. Please enter 1, 2, 3, 4, or 5."。看来,您必须在switch中实现case 3和case 4或编辑该错误消息。


1

使用int.TryParse代替int.Parse,并使用float.tryParse代替float.Parse


0

虽然所有提供的答案似乎都有效,但你所问的问题是

如何防止抛出异常[..]

我想指出的是,你可以通过将抛出 exception 的部分放在 try-catch 块中来实现此目的。这样做的作用是执行 try 中的代码,直到抛出 exception,然后将此 exception 作为参数传递给 catch 部分,在那里你可以处理它:

示例

do
{
    try
    {
         // the code you already have
    }
    catch (Exception ex)
    {
         Console.WriteLine("This is no valid input (" + ex.Message + ")! Try again...");
    }
} while (UserChoice != 5);

当然,首先防止抛出异常是更好的方法(正如所有其他答案所建议的那样),但这种方法同样有效,并且在将来遇到类似问题时更加通用。使用 switch-case 语句进行错误处理是相当常见的做法...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接