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 trialIsaac Barshay
2,609 PointsWhat am I doing wrong?
Quote: "Add input validation to your program by printing “You must enter a whole number.” if the user enters a decimal or something that isn’t a number. Hint: Catch the FormatException."
using System;
namespace Treehouse.CodeChallenges
{
class Program
{
static void Main()
{
bool InputFalse = true;
int Count = 1;
Console.Write("Enter the number of times to print \"Yay!\": ");
string Input = Console.ReadLine();
while (true)
{
if (InputFalse == false)
{
// Prompt user for number of time
Console.Write("Enter the number of times to print \"Yay!\": ");
Input = Console.ReadLine();
InputFalse = true;
}
try
{
int NumberOfTimes = int.Parse(Input);
Console.WriteLine("\"Yay!\"");
if (Count == NumberOfTimes) break;
else Count++;
}
catch(FormatException)
{
Console.WriteLine("You must enter a whole number.");
InputFalse = false;
continue;
}
}
}
}
}
1 Answer
Steven Parker
231,269 PointsYour loop repeats the prompt and input.
You also have a duplicate of the prompt output and a second ReadLine as well, but there should only be one of each. The loop should only enclose the code that prints out the "Yay!" messages if the number given is good, nothing else should be in the loop.
A program built according to the instructions will prompt and accept input one time, and based on the input it will either print "Yay!"s or an error mesage. Either way, it should end. With the loop around the other code it never ends and keeps asking for input.
Allan Clark
10,810 PointsAllan Clark
10,810 Pointswhat is the error you are getting?