【发布时间】:2016-09-28 00:37:48
【问题描述】:
这实际上是我编写的第一个程序(上周一开始学习);我是一个完全的新手。
我的问题是,当程序提示用户输入华氏温度或摄氏温度(期望数字)时,如何防止用户输入无效字符时引发异常???例如,当用户输入“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 msdn.microsoft.com/library/0yd65esw.aspx 或正则表达式,但当您本周开始时,请阅读 try catch 文章
标签: c# validation input