我愚蠢地关闭了一个我认为最近回答过的问题,但我还遇到了另一个问题。
按下输入时,如果没有输入字符,我的代码会崩溃。有办法防止这种情况吗?如果用户输入错误的字符,则会显示错误消息,但如果在未输入任何输入的情况下按下输入,则会崩溃。
我收到的错误消息是未处理的类型' System.FormatException'发生在mscorlib.dll中 附加信息:字符串必须只有一个字符长。
这是我的代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace computerPackage
{
class Program
{
static void Main(string[] args)
{
char computerPackage;
const decimal DELUXE_PACKAGE = 1500;
const decimal SUPER_PACKAGE = 1700;
Console.Write("Input the Computer Package D or S: ");
computerPackage = Char.Parse(Console.ReadLine());
computerPackage = Char.ToUpper(computerPackage);
if (computerPackage == 'D')
{
Console.WriteLine("Cost of Deluxe Computer Package is " + DELUXE_PACKAGE.ToString("C"));
}
else if (computerPackage == 'S')
{
Console.WriteLine("Cost of Deluxe Computer Package is " +
SUPER_PACKAGE.ToString("C"));
}
else
{
Console.WriteLine("Package D or S not entered");
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(); // pause
}
}
}

答案 0 :(得分:0)
按Enter后没有任何字符,程序会尝试解析一个不可能的空字符串,并会给出异常。在解析之前创建检查
static void Main(string[] args)
{
char computerPackage;
const decimal DELUXE_PACKAGE = 1500;
const decimal SUPER_PACKAGE = 1700;
Console.Write("Input the Computer Package D or S: ");
string inp = Console.ReadLine();
if (inp.Length==1)
{
computerPackage = Char.Parse(inp);
computerPackage = Char.ToUpper(computerPackage);
if (computerPackage == 'D')
{
Console.WriteLine("Cost of Deluxe Computer Package is " + DELUXE_PACKAGE.ToString("C"));
}
else if (computerPackage == 'S')
{
Console.WriteLine("Cost of Deluxe Computer Package is " +
SUPER_PACKAGE.ToString("C"));
}
else
{
Console.WriteLine("Package D or S not entered");
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
else
{
Console.WriteLine("Package D or S not entered");
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}