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

Michael Thompson
Michael Thompson
7,427 Points

Why won't it print my else if?

I don't understand why it won't print my else if when the user inputs a negative number. It prints nothing. What am I doing wrong here?

Program.cs
using System;

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



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

          var a = Console.ReadLine();

          try 
          {
            var b = int.Parse(a);

            for(int n=0; n<b; b--)
            {
              if (b > 0)
              {
              Console.Write("Yay!");
              }

              else if (b < 0)
              {
                Console.Write("You must enter a positive number."); 
              }

              else 
              {
                Console.Write("Not a valid input."); continue;
              }

            }
          }
          catch(FormatException)
          {
            Console.Write("You must enter a whole number."); 
          }


        }
    }
}

1 Answer

Steven Parker
Steven Parker
231,269 Points

You need to test for a negative number before the loop.

It doesn't need to be done more than once, and the loop will not run at all if the value of "b" is less than 0.

You also don't need any conditional around the output statement inside the loop. The loop itself controls the number of outputs.

Michael Thompson
Michael Thompson
7,427 Points

I have absolutely no idea how to do that.

Steven Parker
Steven Parker
231,269 Points

Just move the test out of the "for" block and place it before, and you can also eliminate the unneeded conditionals. So the contents of the "try" block could be:

            var b = int.Parse(a);

            if (b < 0)  // test for negative number BEFORE loop
            {
              Console.Write("You must enter a positive number."); 
            }

            for(int n=0; n<b; b--)
            {
              Console.Write("Yay!");
            }
Michael Thompson
Michael Thompson
7,427 Points

I could've sworn I had tried that already. Thank you. I was getting quite frustrated.