Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Basics (Retired) Perfect Final

How do I fix this?

How can I fix this...

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {   int i = 0;
        static void Main()
        {

            Console.Write("Enter the number of times to print \"Yay!\": ");
            string entry = Console.ReadLine();
             while (i <= entry.Convert.ToInt32())
             {
                        Console.WriteLine("Yay!");
                     }   


        }
    }
}

1 Answer

Keli'i Martin
Keli'i Martin
8,227 Points

I can see a couple of things wrong with your code.

First, you should define the int i inside main().

Second, you are using the Convert.ToInt32() method incorrectly. The signature of that method is

public static int ToInt32(
    string value
)

where value is the string you want to convert. So it's proper usage in your code would be

Convert.ToInt32(entry)

Lastly, using a while loop here would work but you are never incrementing the value of i, so the code gets stuck in an infinite loop. This would be easily solved by throwing an i++ after the Console.WriteLine(). You also will probably want to save the value of Convert.ToInt32(entry) to a new int variable. This way, the Convert.ToInt32() method doesn't get called on every iteration of the loop.

Oh and one more thing... The condition you are using for your while loop would print "Yay!" one extra time. Since int i is being initialized to 0, your loop would run from 0 to entry, resulting in one too many iterations. Either initialize i to 1 or change your while condition to use the less than operator instead of the less than or equal to operator.

Here is what the code looks like with these changes made:

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {   
        static void Main()
        {
            int i = 0;
            Console.Write("Enter the number of times to print \"Yay!\": ");
            string entry = Console.ReadLine();
            int num = Convert.ToInt32(entry);
            while (i < num)
            {
                Console.WriteLine("Yay!");
                i++;
            }   
        }
    }
}

That was genius, and thanks for the hand up. Now that I see your solution, I feel that I gave up to soon! Have a good one.