简体   繁体   中英

C# Method Declaring

 public void GetPosNonZeroDouble()
 { 
     double x;

     Console.WriteLine("Enter The Length Of The Side");
     x = double.Parse(Console.ReadLine());
     if (x <= 0)
         Console.WriteLine("Error - input must be a non - zero positive number");
     else
         return x;

     x = double.Parse(Console.ReadLine());
 }

 static void ProcessSquare()
 {
     GetPosNonZeroDouble();
     double side;
     double answer;
     Console.WriteLine();
     side = double.Parse(Console.ReadLine());
     answer = Math.Pow(side, 2);

     Console.WriteLine("The Square Area is {0}", answer);
 }

I am supposed to have a "GetPosNonZeroDouble" which needs to act like this image: c#Question I have declared this method but am unsure how I tell processSquare() to check if the number is < 0 and how to display such by inputing the module. Please assist me with this as i am stuck finding the solution to my problem.

You need to either make the method static, or make it part of a class and call it from an instance of the class. Also, you can't return values from a void method.

public static double GetPosNonZeroDouble()
{ 
    double x = 0;

    while (x <= 0)
    {
        Console.WriteLine("Enter The Length Of The Side");
        if (!double.TryParse(Console.ReadLine(), x) || x <= 0)
        {
            Console.WriteLine("Error - input must be a non - zero positive number");
        }
    }
    return x;
 }
GetPosNonZeroDouble

Is an instance method that you are trying to call from a static method and you can't do that. You need to create an instance of whatever class GetPosNonZeroDouble is in and then invoke it using the dot notation. Have a look here and you should also try some C# tutorials to get you going.

It seems that you don't have experience with methods in general.

As a start, I would recommend you to check the official C# documentation for methods: https://msdn.microsoft.com/en-us/library/vstudio/ms173114(v=vs.100).aspx

For example, your method GetPosNonZeroDouble() does not return anything but you try to return a value with return x; (which would end up in a compiler error).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM