2017-02-27 53 views
1

我正在嘗試使收據能夠輸入字母和數字。收據不允許使用字母

 decimal counter; 
     decimal item; 
     decimal price; 
     decimal subtotal; 
     decimal tax; 
     decimal total; 
     decimal quantity; 

     subtotal = 0; 
     counter = 0; 


     while (counter <= 10) 
     { 
      Console.Write("Item{0}", counter + 1); 
      Console.Write("  \tEnter item: "); 
      item = Convert.ToDecimal(Console.ReadLine()); 
      if (item == 0) 
       break; 
      Console.Write("  Enter price: "); 
      price = Convert.ToDecimal(Console.ReadLine()); 


      counter = counter + 1; 

      Console.Write("  Enter quantity: "); 
      quantity = Convert.ToInt32(Console.ReadLine()); 
      subtotal += price * quantity; 
     } 
     Console.WriteLine("-------------------"); 
     Console.WriteLine("\nNumber of Items:{0}", counter); 
     Console.WriteLine("Subtotal is {0}", subtotal); 
     tax = subtotal * 0.065M; 
     Console.WriteLine("Tax is {0}", tax); 
     total = tax + subtotal; 
     Console.WriteLine("Total is {0}", total); 
     Console.WriteLine("Thanks for shopping! Please come again."); 
     Console.Read(); 

例如,可以說我買一個蘋果和我輸入「蘋果」它說:「進入項目」,然後輸入控管數量和價格。然後我決定我想結束它,所以我輸入0來打破代碼。我有能力輸入數字,但是當我輸入一個字母時,它不起作用。

+1

爲什麼當你輸入字符串爲 '蘋果''decimal'項目? – Sameer

回答

0

如果你想輸入類似"apple"該代碼將無法正常工作:

Console.Write("  \tEnter item: "); 
item = Convert.ToDecimal(Console.ReadLine()); 
if (item == 0) 
    break; 

在這裏你嘗試一些符號(非數字)分析,以decimal - 結果你應該得到的異常。

你的代碼更改爲:

Console.Write("  \tEnter item: "); 
item = Console.ReadLine(); 
if (item == "0") 
    break; 

而且,變化型item

string item; //previously decimal item; 
+0

修復了這個問題,謝謝! – Shade

+0

@Shade,不客氣 –