Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,120 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.