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

Help me with this one (C#)

Hello help me I'm stuck with this one because you have to use multiple catches and I don't know how to that.

the first task: This final code challenge will require you to use almost everything we've covered in this course. You’ll write a program to celebrate completing this course by printing “Yay!” to the screen a given number of times. Write a program that: Prompts the user to enter the number of times to enter “Yay!”. I've done this for you. Leave this as it is. Prints “Yay!” to the screen that number of times (Hint: You’ll need a loop for this. You’ll also need to keep track of how many times the loop has run). You can print them all on the same line or on separate lines. \passed

the second task was this : Add more input validation to your program by printing “You must enter a positive number.” if the user enters a negative number. \passed

and here is the third one where I don't know what to do: Add more input validation to your program by printing “You must enter a positive number.” if the user enters a negative number.

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            var entry = Console.ReadLine();
            int counter  = 0;

            try
            {
            var total = int.Parse(entry);
            while (total > counter)
            {
                    Console.WriteLine("Yay!");
                    counter +=1;
            }
            }

            catch(FormatException)
            {
            Console.WriteLine("You must enter a whole number");
            }
            Console.ReadLine();
        }
    }
}

2 Answers

Steven Parker
Steven Parker
231,248 Points

Detecting a negative input is not done using "try...catch". After parsing the input, you can then perform a simple "if" test to see if the value is less than zero.

Aah thanks!