Search code examples
c#console.writelineint32

using if to display an invalid text


hello I'm just a beginner in C# language I want to learn how to use "if" on this part of the code for example when I type a character or letter input in the console and pressed enter it should display a text "Invalid, please enter a valid value." or something like that. but when I inputted a valid number it should calculate the area of the circle.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jay_trycode
{
    class Program
    {
        static void Main(string[] args)
        {
            //This program allows the user to calculate the area of the circle//
            int radius;
            double area;

            //This asks the user for input about radius
            Console.Write("*****Area of the Circle*****");
            Console.WriteLine("\n\nPlease input the radius: ");
            radius = Convert.ToInt32(Console.ReadLine());

            //This is the given Formula
            area = 3.1415 * radius * radius;

            //This shows the Area of the Circle calculated from the formula
            Console.Write("\nThe Area of the Circle is: " + Math.Round(area, 2));
        }
    }
}

Solution

  • try this

        static void Main(string[] args)
        {
            //This asks the user for input about radius
            Console.Write("*****Area of the Circle*****");
            Console.WriteLine("\n\nPlease input the radius: ");
            if (int.TryParse(Console.ReadLine(), out int radius))
            {
                //Using native math 
                double area = Math.PI * Math.Pow(radius, 2);
                //This shows the Area of the Circle calculated from the formula
                Console.Write("\nThe Area of the Circle is: " + Math.Round(area, 2));
            }
            else
            {
                Console.WriteLine("Invalid input");
            }
        }