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

Josh Boersma
PLUS
Josh Boersma
Courses Plus Student 2,486 Points

Catching Exception Refuses to Compile

Challenge: 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.

I'm at work at and can't look at compile errors. So I have no clue why this isn't working (I'm a CS major and should be doing this easy). Any pointers or directional help would be fantastic.

Program.cs
using System;

namespace Treehouse.CodeChallenges {
    class Program {
        static void Main() {
           int count = 0;
            while (true) {
               try { 
                    Console.WriteLine("Enter the number of times to print \"Yay!\": ");
                    count = Console.ReadLine();
                    //int count = Convert.ToInt32(c);
                    if(count <= 0) {
                        Console.WriteLine("You must enter a whole number.");
                        continue;
                    }
                   if (count == null){
                        Console.WriteLine("You must enter a whole number.");
                        continue;                    
                   }

                    int total = 0;
                    while (total < count) {
                        Console.WriteLine("Yay!");
                        total = total + 1;
                    }
                   break;
                }   //try
                catch(FormatException) {
                    Console.WriteLine("You must enter a whole number.");
                    continue;
                }//catch
            }//while
        }  //Main
    }//class
}//namespaces

1 Answer

Steven Parker
Steven Parker
230,274 Points

You have an outer loop that prevents the program from ending if bad values are entered.

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 extra loop it never ends.