Question

this is my first post, apologies for mistakes I may make and bad formatting.

The issue I am having is that the second time it loops int whichAccount = int.Parse(Console.ReadLine()); does not work and won't take my input. It raises the exception "Input string was not in a correct format". The first time it loops it all works fine. What is am I doing wrong? Thanks.

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;


        }
    }
Was it helpful?

Solution

The problem is due to y = (char)Console.Read();

Consider using the following to read the first character in the input. It will ensure the entire input is read which will not leave any additional characters or empty spaces in the remaining console text:

y = Console.ReadLine().Trim()[0];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top