Home > Net >  Cannot use Variable in Method
Cannot use Variable in Method

Time:12-13

I have a problem to use my radius im the Method GetCircleArea(). Please help. I am sitting here and dont know what to do anymore.

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

namespace Programmieraufgabe_5
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Gebe einen Radius ein: ");
            double rad = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Die Fläche eines Kreises mit dem Radius {0}cm beträgt {1}cm²", rad, GetCircleArea());

            Console.ReadKey();

        }

        static double GetCircleArea()
        {
            double area = Math.PI * radius * radius;
            return area;
        }
    }
}

Thank you. For the answers!

CodePudding user response:

The answer to your question is that you cannot access the variables of other Methods in any Method you want that simple. The easiest way to do this is to add a parameterList to the GetCircleArea Method.

So write:

 static double GetCircleArea(double radius)

instead of:

static double GetCircleArea()`

Also when you use the method, write what for a parameter you want to give to the Method. In your case, it would be the rad variable from Main. So you can write:

Console.WriteLine("Die Fläche eines Kreises mit dem Radius {0}cm beträgt {1}cm²", rad, GetCircleArea(rad));

P.S. If you want that you can put the radius in the same Line with the Text Gebe einen Radius ein: you can use Console.Write() instead of Console.WriteLine(). Because with Console.Write you can proceed in the same Line. Then you use Console.ReadLine() and switch the Line nevertheless.

I hope I could help you. :)

  • Related