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 trialMichael Thompson
7,427 PointsWhy 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?
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
231,269 PointsYou 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
7,427 PointsMichael Thompson
7,427 PointsI have absolutely no idea how to do that.
Steven Parker
231,269 PointsSteven Parker
231,269 PointsJust 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:
Michael Thompson
7,427 PointsMichael Thompson
7,427 PointsI could've sworn I had tried that already. Thank you. I was getting quite frustrated.