我的C#项目获取值不能为空错误
c#
System.ArgumentNullException: '值不能为空。(参数')'
我收到此错误 ^。
我想在产品代码上按 CTRL Z 后,它会停止循环并继续下一行代码。但是我输入了 ctrl z 并且它转到 Quantity 行并在那之后中断。如果有人知道如何解决此错误,我认为这是因为 Quantity 无法返回 Null 值,因为它不像产品那样设置,但我找不到解决方法。
public class Transaction
{
public string Name { get; set; }
public int productCode { get; set; }
public int productQuantity { get; set; }
//constructor
public Transaction(string cName)//, int pCode, int pQuantity
{
Name = cName;
}
public void AssessProducts()
{
int codeInput;
int qtyInput = 0;
decimal transTotal = 0;
double qty201 = 0;
double qty556 = 0;
double count201 = 0;
double count556 = 0;
double count558 = 0;
double count909 = 0;
double count910 = 0;
Console.WriteLine("Product Code: ");
string ctrlzInput = Console.ReadLine();
Console.WriteLine("Quantity: ");
qtyInput = int.Parse(Console.ReadLine());
while (ctrlzInput != null)
{
codeInput = int.Parse(ctrlzInput);
if (codeInput == 201)
{
count201 = count201 + 19.99;
}
else if (codeInput == 556)
{
count556 = count556 + 59.99;
}
else if (codeInput == 558)
{
count558 = count558 + 20.50;
}
else if (codeInput == 909)
{
count909 = count909 + 105.99;
}
else if (codeInput == 910)
{
count910 = count910 + 16.99;
}
else
{
Console.WriteLine("Error! Wrong product code.");
}
transTotal = (decimal)((double)transTotal + count201 + count556 + count558 + count909 + count910);
qty201 = qty201 + qtyInput;
qty556 = qty556 + qtyInput;
Console.WriteLine("Product Code: ");
ctrlzInput = Console.ReadLine();
Console.WriteLine("Quantity: ");
qtyInput = int.Parse(Console.ReadLine());
}
Console.WriteLine($"Customer Name: {Name} nn");
Console.WriteLine("Items Ordered:nn");
Console.WriteLine("Product # Product Name Price Qty Line Totaln");
if (count201 >= 1)
{
Console.Write($"Product 210 - ACME Anvil @ $19.99 *{qty201} = {qty201 * 19.99} n");
}
if (count556 >= 1)
Console.Write($"Product 556 - ACME Dynamite @ $59.99 *{qty556} = {qty556 * 59.99} n");
}
}
回答
从文档:
退货
细绳
输入流中的下一行字符,或者
null如果没有更多行可用。
和:
如果在方法从控制台读取输入时按下Ctrl+Z字符,则方法返回
null。这使用户能够ReadLine在循环调用该方法时阻止进一步的键盘输入。