Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Basics (Retired) Perfect Final

c# basics final challenge task 1of2

add input validation to the below program by printing "you must enter a whole number." if the user enters a decimal or something that isn't a number. .wrap all of the code contained in the main method in a try/catch block . the catch block should catch formatException execeptions .inside of the catch block, output to the console the message "you must enter a whole number."

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            var entry = Console.ReadLine();

            int counter = 0;
            try
            {
              var total = int.Parse(entry);
             while(total > counter)
            {
              Console.WriteLine("Yay!");
              counter +=1;
             }
             }
            catch(FormatException)
                Console.WriteLine("You must enter a whole number");
        }
          Console.ReadLine();
            }
        }
    }
}

2 Answers

Steven Parker
Steven Parker
218,679 Points

It looks like the "catch" block is missing an open brace, and there seems to be one to many closing braces at the end of the program.

Also, that extra "ReadLine" at the end isn't asked for in the instructions.

thank you

This is how I did it. if it helps... THEN you know what to do?

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            string input = Console.ReadLine();

            int i = 0;
            try
           {     
                int count = int.Parse(input);

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