2013-04-02 18 views
0

我不斷收到索引超出範圍例外。我必須得到銷售人​​員編號和產品編號,然後在顯示總計之前獲得價格。C#矩形陣列有3個銷售人員和5個產品

我不知道發生了什麼,因爲計算似乎是正確的。無論什麼錯誤都可能是我無法想象的小事。感謝幫助。在C#

class Program 
{ 
    static void Main(string[] args) 
    { 

     decimal[,] sales = new decimal[5, 3]; 
     int spnum; 

     Console.WriteLine("Enter your Sales Person Number (type 999 to exit): "); 
     spnum = Convert.ToInt32(Console.ReadLine()); 

     while(spnum != 999) 
     { 
      int prodnum; 
      decimal price; 
      decimal amount = 0; 

     Console.WriteLine("Enter the product number: "); 
     prodnum = Convert.ToInt32(Console.ReadLine()); 

     Console.WriteLine("Enter the total for the product: "); 
     price = Convert.ToDecimal(Console.ReadLine()); 

     if (spnum >= 1 && spnum <= 3 && prodnum >= 1 && prodnum <= 5 && price >= 0) 
     { 
      sales[spnum - 1, prodnum - 1] += amount; 
     } 
     else 
     { 
      Console.WriteLine("You have entered an invalid number. Please try again."); 
     } 

     Console.WriteLine("Enter your salesperson (type 999 to exit): "); 
     spnum = Convert.ToInt32(Console.ReadLine()); 

     } 

     decimal[] total = new decimal[4]; 

     Console.WriteLine("\n{0,10}{1,16}{2,16}{3,16}{4,12}", "Product", "SalesPerson1", "SalesPerson2", "SalesPerson3", "Total"); 

       for (int row = 0; row < 5; row +=1) 
     { 
      decimal prodtot = 0M; 
        Console.Write("{0,10}", (row+=1)); 

        for (int colum = 0; colum < 3; colum +=1) 
        { 
         Console.Write("{0,16:C}", sales[row, colum]); 
         prodtot += sales[row, colum]; 
         total[colum] += sales[row, colum]; 
        } 
        Console.Write("{0,10:C}", total); 

        for (int c = 0; c < 3; c += 1) 
        { 
         Console.Write("{0,16:C}", total[c]); 
         Console.ReadLine(); 
        } 
     } 

    } 

回答

2

數組索引基於0。在你的情況下,他們從0到2和0至4

1

您申報銷售爲:

decimal[,] sales = new decimal[5, 3]; 

然後你這裏使用它們:

if (spnum >= 1 && spnum <= 3 && prodnum >= 1 && prodnum <= 5 && price >= 0) 
{ 
    sales[spnum - 1, prodnum - 1] += amount; 
} 

prodnum - 1可以大於2