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

Delbert Harry
Delbert Harry
1,794 Points

What is wrong with this code. It works in VS2015?

fails code check.

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            int iRepeat = 0;
            bool x = true;

            while(x)
            {
               try
               {
                   Console.WriteLine("Enter a number: ");
                   iRepeat = int.Parse(Console.ReadLine());   
                   x = false;
               }
               catch(FormatException)
               {   
                   Console.WriteLine("Non valid number entered.");
               }    
               catch(ArgumentNullException)
               {
                   Console.WriteLine("Not valid number entered.");
               }
            }

            int i = 0;
            while (i <= iRepeat)
            {
                  Console.Write("Enter the number of times to print \"Yay!\": ");
                  i++;
            }
        }
    }
}

2 Answers

Benjamin Larson
Benjamin Larson
34,055 Points

Even if this code properly compiles in VS, it's not meeting the exact requirements of the code challenge.

Your highest level while loop while(x) is unnecessary and should be removed. By extension, everything involving the x variable can be deleted too. You don't need a second catch block for the ArgumentNullException, you can simply add an IF statement inside the try block to check if the number is not positive.

The while block should loop through this:

Console.WriteLine("Yay!");

and the prompt you have should be moved up above the try block as it only needs to asked one time. Your loop will technically run 1 too many times as is. You either need to set i = 1, or change the condition to: (i < iRepeat)

Hopefully that gives you enough ideas to take another stab at it.