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 trialPatrick Parreno
1,779 PointsInput Validation
Can someone help me out with my code. Its asking for input validation for a negative number input.
using System;
namespace Treehouse.CodeChallenges
{
class Program
{
static void Main()
{
try
{
Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
int input2 = int.Parse(input);
while (input2 > 0)
{
if (input2 != 0)
{
input2 -= 1;
Console.WriteLine("Yay!");
}
else
{
break;
}
}
}
catch (FormatException)
{
Console.WriteLine("you must enter a whole number");
}
catch
{
Console.WriteLine("you must enter a positive number");
}
}
}
}
1 Answer
Steven Parker
231,269 PointsYou don't need a catch to check for a negative input.
You can do this easily after you have parsed the input into a number. Then you can test the number in an if statement to see if it is negative, and if so give the feedback and end the program.
Also, you don't need that if inside the while, because the loop condition itself is enough to cause the loop to stop.