这段代码对我有用,除了它只检查一次重复项,如果用户再次输入相同的整数,程序将第二次接受它。如何使该程序不接受该条目,无论用户输入多少次?
int[] shippedOrderNumbers = new int[5];
Console.WriteLine("Please Input first Shipping Number: ");
shippedOrderNumbers[0] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Input second Shipping Number: ");
shippedOrderNumbers[1] = Convert.ToInt32(Console.ReadLine());
if (shippedOrderNumbers[0] == shippedOrderNumbers[1])
{
Console.WriteLine("A dublicate number is not allowed please try again: ");
shippedOrderNumbers[1] =Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Please Input third Shipping Number: ");
shippedOrderNumbers[2] = Convert.ToInt32(Console.ReadLine());
if (shippedOrderNumbers[0] == shippedOrderNumbers[2] || shippedOrderNumbers[1] == shippedOrderNumbers[2])
{
Console.WriteLine("A dublicate number is not allowed please try again: ");
shippedOrderNumbers[2] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Please Input fourth Shipping Number: ");
shippedOrderNumbers[3] = onvert.ToInt32(Console.ReadLine());
if (shippedOrderNumbers[0] == shippedOrderNumbers[3] || shippedOrderNumbers[1] == shippedOrderNumbers[3] || shippedOrderNumbers[2] == shippedOrderNumbers[3])
{
Console.WriteLine("A dublicate number is not allowed please try again: ");
shippedOrderNumbers[3] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Please Input fifth Shipping Number: ");
shippedOrderNumbers[4] = Convert.ToInt32(Console.ReadLine());
if (shippedOrderNumbers[0] == shippedOrderNumbers[4] || shippedOrderNumbers[1] == shippedOrderNumbers[4] || shippedOrderNumbers[2] == shippedOrderNumbers[4] || shippedOrderNumbers[3] == shippedOrderNumbers[4])
{
Console.WriteLine("A dublicate number is not allowed please try again: ");
shippedOrderNumbers[4] = Convert.ToInt32(Console.ReadLine());
}
我认为使用通用列表而不是数组会更好。还可以使用简单循环来简化代码。有关示例,请参阅以下内容。
IList<int> shippedOrderNumbers = new List<int>();
for (int = 0; i < 5; i++)
{
Console.WriteLine("Please input the Shipping Number: ");
int shippingNumber;
if (!Int.TryParse(Console.ReadLine(), out shippingNumber)
{
Console.WriteLine("Your shipping number is not an integer");
}
if (shippedOrderNumbers.Contains(shippingNumber))
{
Console.WriteLine("This shipping number has already been entered.");
}
else
{
shippedOrderNumbers.Add(shippingNumber);
Console.WriteLine("Thanks for submitting your shipping number.");
}
}
附言。我在记事本中写了这个,所以它可能不起作用,但应该为您提供有关如何解决问题的一般指南。
沿着这些思路应该这样做:
var shippedOrderNumbers = new List<int>();
var validOrderNumbers = 0;
while(validOrderNumbers < 5)
{
Console.WriteLine("Input order number:");
var nextOrderNumber = Convert.ToInt32(Console.ReadLine());
if(shippedOrderNumbers.Any(son => son == nextOrderNumber))
{
Console.WriteLine("Duplicate order number. Please enter another");
continue;
}
shippedOrderNumbers.Add(nextOrderNumber);
validOrderNumbers++;
}