C# C# Basics (Retired) Perfect Final

Alona Szeinwald
Alona Szeinwald
1,603 Points

I am stuck with the Challenge Task, have 2 compiler errors

using System;

namespace Treehouse.CodeChallenges { class Program { static void Main() {

            Console.Write("Enter the number of times to print \"Yay!\": ");
            string input = Console.ReadLine();

        try
        {   

                int count = int.Parse(input);

        }
         catch(FormatException)
        {
            Console.WriteLine("You must enter a whole number.");
              break;
         }  
                int i = 0;
                while(i < count)
                {
                    i += 1;   
                    Console.WriteLine("Yay!");
                }




    }
}

}

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {

                Console.Write("Enter the number of times to print \"Yay!\": ");
                string input = Console.ReadLine();

            try
            {   

                    int count = int.Parse(input);

            }
             catch(FormatException)
            {
                Console.WriteLine("You must enter a whole number.");
                  break;
             }  
                    int i = 0;
                    while(i < count)
                    {
                        i += 1;   
                        Console.WriteLine("Yay!");
                    }




        }
    }
}
Eric Holt
Eric Holt
Full Stack JavaScript Techdegree Student 11,812 Points

You should initialize the count outside the try block. If it is unable to parse the data it would be null. You can't use break inside the catch. The break is used inside of switch statements and loops.

2 Answers

Emmanuel C
Emmanuel C
7,626 Points

The Challenge says to wrap all of the code in the main inside a try catch, including the Console.ReadLine() and while loop. One of the errors that were being thrown was that count doesn't exist in the current context. That is because the int count is being declared inside the try block but its being used outside of the block meaning that its going out of scope, so count only exist inside that try block. Putting that while loop inside the try catch will fix that.

Second thing is that there is a break; inside the catch block. Break statements are only for loops and switch case statements, which breaks it out of that iteration. However the catch block is not a loop so its not necessary to use one there.