使用一些简单的逻辑,根据跟踪号确定邮政承运人。我正在尝试将跟踪号放入一个名为“ trackingNumberArray”的数组中,然后使用一些if语句来比较该数组的各个项目以确定载体。这是我拥有的代码,但似乎仍然无法使其正常工作。任何提示/指导将不胜感激!
static void Main(string[] args)
{
string trackingNumber = "1Z204E380338943508";
string[] trackingNumberArray = new string[] {trackingNumber};
if (trackingNumberArray.Contains("1Z"))
{
string carrierName = "UPS";
Console.WriteLine($"Carrier Name" + carrierName);
}
else if (trackingNumberArray.Length >= 12 && trackingNumberArray.Length < 14 && !!trackingNumberArray.Contains("1Z"))
{
string carrierName = "Fedex";
Console.WriteLine($"Carrier Name" + carrierName);
}
else if (trackingNumberArray.Length >= 20 && trackingNumberArray.Length < 22 && !trackingNumberArray.Contains("1Z"))
{
string carrierName = "USPS";
Console.WriteLine($"Carrier Name" + carrierName);
}
else
{
string carrierName = null;
Console.WriteLine($"did not work" + carrierName);
}
}
答案 0 :(得分:1)
您不必将跟踪号放入数组中,而只需将其保留为字符串即可。然后,您的其余代码应使用该字符串。您也不需要"1Z"
的多余检查,因为它在第一个条件中:
static void Main()
{
string trackingNumber = "1Z204E380338943508";
string carrierName = null;
if (trackingNumber.Contains("1Z"))
{
carrierName = "UPS";
}
else if (trackingNumber.Length >= 12 && trackingNumber.Length < 14)
{
carrierName = "FedEx";
}
else if (trackingNumber.Length >= 20 && trackingNumber.Length < 22)
{
carrierName = "USPS";
}
if (carrierName == null)
{
Console.WriteLine("Did not work.");
}
else
{
Console.WriteLine($"Carrier name: {carrierName}");
}
GetKeyFromUser("\nPress any key to exit...");
}
然后您可以根据代码创建一个static
方法:
public static string GetCarrierName(string trackingNumber)
{
if (trackingNumber == null) return null;
if (trackingNumber.Contains("1Z")) return "UPS";
if (trackingNumber.Length >= 12 && trackingNumber.Length < 14) return "FedEx";
if (trackingNumber.Length >= 20 && trackingNumber.Length < 22) return "USPS";
return null;
}
并像这样使用它:
static void Main()
{
string carrierName = GetCarrierName("1Z204E380338943508");
if (carrierName == null)
{
Console.WriteLine("Unknown tracking id format.");
}
else
{
Console.WriteLine($"Carrier name: {carrierName}");
}
GetKeyFromUser("\nPress any key to exit...");
}
答案 1 :(得分:0)
trackingNumberArray.Contains("1Z")
这将不起作用,因为您的数组由单个字母组成。如果要查找字符串,请使用原始字符串。
trackingNumber.Contains("1Z")
此外,也不需要此位,因为它位于“ else”中,只有在它为真时才能到达。
&& !trackingNumberArray.Contains("1Z")