【发布时间】:2019-07-21 16:48:33
【问题描述】:
我自己正在学习 C#(不是家庭作业),并且在有用户输入时对方法重载感到困惑。
我正在做一个练习,允许用户输入一个项目的出价金额。我需要包含 3 个重载方法(int、double、string)。 (练习说使用双精度而不是十进制。)
我知道如何编写重载方法,我的困惑来自于用户输入。如果我接受输入(ReadLine)作为字符串,它选择字符串方法,如果我接受输入作为 int,则调用 int 方法。我该如何处理?我使用 tryParse 吗?如何使用 3 种可能的输入法(int、double、string)来做到这一点?
另外,为了增加一个令人沮丧的转折,要接受的字符串必须是数字,并且前面有“$”符号或数字后跟“美元”。我希望我在下面的代码中正确地完成了这一点。不知道如何按字符串修剪,所以我不得不按字符来做...
希望有一个基本/简单的解释,因为我还没有学到任何太花哨的东西。
谢谢!
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);
}
}
}
【问题讨论】:
-
请不要在问题标题中包含有关所用语言的信息,除非没有它就没有意义。标记用于此目的。
-
谢谢,新来的网站...
标签: c# user-input overloading