gpt4 book ai didi

C# 按 Enter 键时出错 - 程序崩溃

转载 作者:行者123 更新时间:2023-12-02 03:59:26 29 4
gpt4 key购买 nike

我愚蠢地关闭了一个我认为最近已得到解答的问题,但我遇到了另一个问题。

在没有输入字符的情况下按下 Enter 键时,我的代码崩溃了。有办法防止这种情况吗?如果用户输入错误字符,则错误消息有效,但如果在没有放置任何输入的情况下按下 Enter 键,则会崩溃。

我收到的错误消息是在 mscorlib.dll 中发生了“System.FormatException”类型的未处理异常附加信息:字符串必须恰好是一个字符长。

这是我的代码:

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
}
}
}

最佳答案

在您按下不带任何字符的回车键后,您的程序会尝试解析一个空字符串,这是不可能的,并且会给出异常。像这样在解析之前创建检查

    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();

}

关于C# 按 Enter 键时出错 - 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37894606/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com