I'm having an issue with calling methods from another class in C#. I haven't been doing this long (3 weeks to be exact) and don't get the ideas behind calling methods. I have declared everything as public to try to make it easier but it isn't working for me just yet. Any help at all would be very much appreciated. Here is the code in question, I want to use a method in an if statement to calculate the area of various simple shapes however at the output stage I get "That is not a valid choice"
namespace Area_Calculator
{
public class Area
{
public static int Square(int side)
{
int i, A;
Console.WriteLine("Please enter the length of the side of the square");
i = Convert.ToInt16(Console.ReadLine());
A = i * i;
return A;
}
public static int Rectangle(int width, int height)
{
int i, j, A;
Console.WriteLine("Please enter the width of the rectangle");
i = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Please enter the height of the rectangle");
j = Convert.ToInt16(Console.ReadLine());
A = i * j;
return A;
}
public static double Triangle(int width, int height)
{
double i, j, A;
Console.WriteLine("Please enter the width of the triangle");
i = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter the height of the triangle");
j = Convert.ToDouble(Console.ReadLine());
A = (.5 * i * j);
return A;
}
public static double Circle(int radius)
{
int i;
double A;
Console.WriteLine("Please enter the radius of the circle");
i = Convert.ToInt16(Console.ReadLine());
A = (i * Math.PI);
return A;
}
}
class Program
{
static void Main(string[] args)
{
int x, i, j;
i = 0;
j = 0;
Console.WriteLine("Please select what type of shape you wish to find the area of:\n1. Square\n2. Rectangle\n3. Triangle\n4. Circle\n");
x = Convert.ToInt16(Console.ReadLine());
Area r = new Area();
if (x == 1)
{
Area.Square(i);
}
if (x == 2)
{
Area.Rectangle(j, i);
}
if (x == 3)
{
Area.Triangle(j, i);
}
if (x == 4)
{
Area.Circle(i);
}
else
{
Console.WriteLine("That is an invalid choice");
}
Console.ReadKey();
}
}
}
You'll currently always see "That is an invalid choice" unless x is 4... because the final if
/`else is disconnected from all the rest.
You could change it to use else if
everywhere, like this:
if (x == 1)
{
...
}
else if (x == 2)
{
...
}
else if (x == 3)
{
...
}
else if (x == 4)
{
...
}
else
{
...
}
... but it would be simpler to use a switch
statement:
switch (x)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
default:
...
break;
}
That better expresses your intention of "I want to execute exactly one of these branches, based on a simple selection on x
, with a "default" branch if x
isn't any of the known values."
See more on this question at Stackoverflow