C# C# Basics (Retired) Perfect Final

Ankit Biswas
Ankit Biswas
280 Points

I got stuck in a challenge please help me Code isn't running because of compiler error. If else problem.

Add more input validation to the program by printing "You must enter a positive number." if the user enters a negative number.

Add an if/else conditional statement just after parsing the user's provided input to an integer Write a conditional expression to ensure that the remainder of the code in the try block is only executed if the user provides a non-negative number If the user enters a negative number, output to the console the message "You must enter a positive number."?

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            string input = Console.ReadLine();
             int count = int.Parse(input);
             if(count > 0)
        {

            try
            {

            int i = 0;
            while(i < count)
            {
                i += 1;   
                Console.WriteLine("Yay!");
            }
            }
            }
            else
            {
                Console.WriteLine("You must enter a positive number.");

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

                }

        }
    }
}

2 Answers

Steven Parker
Steven Parker
173,603 Points

The "try" and "catch" must be in the same code block and have no other code in between. In the code shown here, neither of those is true.

Formatting the code so that each block is indented would make it easier to see that the "try" is inside the "if" conditional block, but the "catch" comes after the "else" block.

You can restructure the code so that the "if" and "else" are both completely inside the "try" block to fix this.

Here is the complete solution to the challenge

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            string input = Console.ReadLine();
            try{
            int count = int.Parse(input);
            if(count > 0){
            int i = 0;
            while(i < count)
            {
                i += 1;   
                Console.WriteLine("Yay!");
            }
            } else{
                Console.WriteLine("You must enter a positive number.");
            }
            } catch(FormatException){
                Console.WriteLine( "You must enter a whole number.");
            }
        }
    }
}