AS 2019 Re-enter Filename if incorrect

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Issue

At the moment, if the user enters a filename that doesn't exist the game produces an error code and then exits. It would be better to add the additional code for the user to be asked again.

SetupBoard

This is the current method for SetupBoard:

        private static void SetUpBoard(string[,] board, int[,] a, int[,] b, ref bool fileFound)
        {
            string fileName = "game1.txt";
            Console.Write("Do you want to load a saved game? (Y/N): ");
            string answer = Console.ReadLine();
            if (answer == "Y" || answer == "y")
            {
                Console.Write("Enter the filename: ");
                fileName = Console.ReadLine();
            }
            try
            {
                StreamReader filehandle = new StreamReader(fileName);
                fileFound = true;
                LoadPieces(filehandle, a);
                LoadPieces(filehandle, b);
                filehandle.Close();
                CreateNewBoard(board);
                AddPlayerA(board, a);
                AddPlayerB(board, b);
            }
            catch (Exception)
            {
                DisplayErrorCode(4);
            }

        }

In order to repeat the options for the user, a do..while loop would work really well. It will allow the user to enter the details correctly in the first instance, and repeatedly ask until it is correctly filled in.

   private static void SetUpBoard(string[,] board, int[,] a, int[,] b, ref bool fileFound)
   {
       do // new do for the do..while loop
       {  // bracket to enclose the code below      
            string fileName = "game1.txt";
            Console.Write("Do you want to load a saved game? (Y/N): ");
            string answer = Console.ReadLine();
            if (answer == "Y" || answer == "y")
            {
                Console.Write("Enter the filename: ");
                fileName = Console.ReadLine();
            }
            try
            {
                StreamReader filehandle = new StreamReader(fileName);
                fileFound = true;
                LoadPieces(filehandle, a);
                LoadPieces(filehandle, b);
                filehandle.Close();
                CreateNewBoard(board);
                AddPlayerA(board, a);
                AddPlayerB(board, b);
            }
            catch (Exception)
            {
                DisplayErrorCode(4);
            }
        } // closing bracket for the do..while loop
        while(!fileFound); // while for the do..while loop
   }