我正在自己学习 C#(不是家庭作业),并且对存在用户输入时的方法重载感到困惑。
我正在做一个练习,允许用户输入某个项目的出价金额。我需要包含 3 个重载方法(int、double、string)。 (练习中要求使用 double 而不是十进制。)
我知道如何编写重载方法,我的困惑来自用户输入。如果我接受输入(ReadLine)作为字符串,它会选择 string 方法,如果我接受输入作为 int,则调用 int 方法。我该如何处理这个问题?我使用 tryParse 吗?如何使用 3 种可能的输入方法(int、double、string)来做到这一点?
此外,要添加一个令人沮丧的扭曲,要接受的字符串必须是数字,并且前面带有“$”符号或数字后跟“dollars”。我希望我在下面的代码中正确完成了这一点。不确定如何按字符串修剪,所以我必须按字符进行修剪...
希望得到一个基本/简单的解释,因为我还没有学到任何太花哨的东西。
谢谢!
namespace Auction
{
class Program
{
static void Main(string[] args)
{
string entryString;
//int entryInt; // do I need this?
//int entryDouble; // do I need this?
double bidNum;
const double MIN = 10.00;
Console.WriteLine("\t** WELCOME TO THE AUCTION! **\n");
Console.Write("Please enter a bid for the item: ");
entryString = Console.ReadLine().ToLower();
double.TryParse(entryString, out bidNum); // this turns it into a double...
BidMethod(bidNum, MIN);
Console.ReadLine();
}
private static void BidMethod(int bid, double MIN)
{ // OVERLOADED - ACCEPTS BID AS AN INT
Console.WriteLine("Bid is an int.");
Console.WriteLine("Your bid is: {0:C}", bid);
if (bid >= MIN)
Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN);
else
Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN);
}
private static void BidMethod(double bid, double MIN)
{ // OVERLOADED - ACCEPTS BID AS A DOUBLE
Console.WriteLine("Bid is a double.");
Console.WriteLine("Your bid is: {0:C}", bid);
if (bid >= MIN)
Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN);
else
Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN);
}
private static void BidMethod(string bid, double MIN)
{ // OVERLOADED - ACCEPTS BID AS A STRING
string amount;
int amountInt;
if (bid.StartsWith("$"))
amount = (bid as string).Trim('$'); // Remove the $
if (bid.EndsWith("dollar"))
amount = bid.TrimEnd(' ', 'd', 'o', 'l', 'l', 'a', 'r', 's');
else
amount = bid;
Int32.TryParse(amount, out amountInt); // Convert to Int
Console.WriteLine("Bid is a string.");
Console.WriteLine("Your bid is: {0:C}", bid);
if (amountInt >= MIN)
Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN);
else
Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN);
}
}
}
最佳答案
假设您希望支持输入美元金额的各种方式,那么我建议您使用 TryParse
的想法可行:
- 首先使用
int.TryParse
- 因为int
是最严格的(不 允许小数点等) - 第二次使用
double.TryParse
- 最后,如果这些都不起作用,请保留为字符串。
关于c# - 带用户输入的重载方法 (ReadLine()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22202329/