Reputation: 1
internal class Invoice
{
public static decimal[] Total =
{
InvoiceLineItem.quantity[0] * InvoiceLineItem.pricePerUnit[0],
InvoiceLineItem.quantity[1] * InvoiceLineItem.pricePerUnit[1],
InvoiceLineItem.quantity[2] * InvoiceLineItem.pricePerUnit[2],
InvoiceLineItem.quantity[3] * InvoiceLineItem.pricePerUnit[3],
InvoiceLineItem.quantity[4] * InvoiceLineItem.pricePerUnit[4],
InvoiceLineItem.quantity[5] * InvoiceLineItem.pricePerUnit[5],
};
private decimal total1;
private decimal total2;
public void Customer1()
{
for (var i = 0; i < 3; i++)
Console.WriteLine(String.Format("{0,-15} {1,-20} {2,-15} {3,-15} {4,-10}",
InvoiceLineItem.productNumber[i],
InvoiceLineItem.description[i],
InvoiceLineItem.quantity[i],
InvoiceLineItem.pricePerUnit[i],
InvoiceLineItem.Total[i]));
}
public void Customer2()
{
for (var k = 3; k <= 5; k++)
{
Console.WriteLine(String.Format("{0,-15} {1,-20} {2,-15} {3,-15:C} {4,-10:C}",
InvoiceLineItem.productNumber[k],
InvoiceLineItem.description[k],
InvoiceLineItem.quantity[k],
InvoiceLineItem.pricePerUnit[k],
Total[k]));
}
}
public void Customer1Total()
{
for (var i = 0; i <= 2; i++)
{
total1 += Total[i];
Console.WriteLine(String.Format("\nTotal of Customer 1:{0:C}", total1));
}
}
}
I'm having a hard time printing my for loop in method Customer1Total()
just once. I need the output total1
to only print once but it prints 3 times adding the totals incrementally. Basically I only need the last result of this for loop but I see all of the increments. Also for extra information I'm calling the method customer1total
in my main for it to print.
Thank you.
Upvotes: 0
Views: 2416
Reputation: 1573
Your Console.WriteLine
statement is inside the loop body, move it after to have it execute after the loop has finished:
for(int i = 0; i <= 2; i++)
{
total1 += Invoice.Total[i];
}
Console.WriteLine(String.Format("\nTotal of Customer 1:{0:C}", total1));
Also, be aware that because total1
is a class level variable, its value will persist between calls to Customer1Total()
, resulting in it increasing every time the function is called.
Upvotes: 0
Reputation: 2465
public void Customer1Total()
{
for(int i = 0; i <= 2; i++)
{
total1 += Invoice.Total[i];
}
//Move write line outside the loop
Console.WriteLine(String.Format("\nTotal of Customer 1:{0:C}", total1));
}
Upvotes: 1