2013-08-22 46 views
0

這是我的第一篇文章,對我可能犯的錯誤和格式不好的道歉。int whichAccount = int.Parse(Console.ReadLine());不工作第二循環

我遇到的問題是第二次循環 int whichAccount = int.Parse(Console.ReadLine());不起作用,不會接受我的意見。它引發了異常「輸入字符串格式不正確」。第一次循環它一切正常。我做錯了什麼?謝謝。

class ATM 
{ 

    const int SAVING_ACCOUNT = 1; 
    const int DEBIT_CARD = 2; 
    const int CREDIT_CARD = 3; 
    const int INVESTMENT_ACCOUNT = 4; 


    static double[] accountBalances = { 0.0, 1001.45, 850.0, -150.0, 10000.0 }; 

    static string[] accountNames = { "", "Savings Account", "Debit Card", 
             "Credit Card", "Investment Account" }; 


    static void Main() 
    { 
     char y; 

     do { 
      Console.Write("\tSAVING_ACCOUNT = 1;\n\tDEBIT_CARD = 2;\n\tCREDIT_CARD = 3;\n\tINVESTMENT_ACCOUNT = 4;\n\nPlease select account: "); 

      int whichAccount = Int32.Parse(Console.ReadLine()); 

      DisplayBalance(whichAccount); 

      Console.Write("\nDo you wish to see the balance of another account? Y/N: "); 
      y = (char)Console.Read(); 
     } while (Char.IsLetter(y)); 
    } 

    static void DisplayBalance(int whichAccount) 
    { 
     switch (whichAccount) 
     { 
      case 1: Console.WriteLine("\nAccount Balance of Savings Account = ${0}", accountBalances[1]); 
        DateTime date = DateTime.Now; 
        Console.WriteLine("Current Date: {0} ", date); 

       break; 
      case 2: Console.WriteLine("{0}", accountBalances[2]); 
       break; 
      case 3: Console.WriteLine("{0}", accountBalances[3]); 
       break; 
      case 4: Console.WriteLine("{0}", accountBalances[4]); 
       break; 


     } 
    } 

回答

0

的問題是由於y = (char)Console.Read();

考慮使用以下來讀取在輸入第一個字符。它將確保讀取整個輸入,而不會在其餘控制檯文本中留下任何其他字符或空白空間:

y = Console.ReadLine().Trim()[0]; 
+0

Huzzah it work!感謝您的快速回復,我很感激。 – user2281248

+0

@ user2281248沒問題。希望我能提供更好的解釋,但它將不得不做:) – Inisheer