gpt4 book ai didi

c# - 从另一个类调用方法时遇到问题

转载 作者:行者123 更新时间:2023-11-30 19:24:43 24 4
gpt4 key购买 nike

我在使用 C# 调用另一个类的方法时遇到问题。我并没有做这么长时间(准确地说是 3 周),也不了解调用方法背后的想法。我已将所有内容都宣布为公开以尝试使其更容易,但它对我来说还不起作用。任何帮助都将不胜感激。这是有问题的代码,我想在 if 语句中使用一种方法来计算各种简单形状的面积,但是在输出阶段我得到“这不是一个有效的选择”

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();
}
}
}

最佳答案

你目前总是会看到“这是一个无效的选择”,除非 x 是 4... 因为 final if/`else 与所有其他选项断开连接.

可以将其更改为在任何地方都使用else if,如下所示:

if (x == 1)
{
...
}
else if (x == 2)
{
...
}
else if (x == 3)
{
...
}
else if (x == 4)
{
...
}
else
{
...
}

...但是使用 switch 语句会更简单:

switch (x)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
default:
...
break;
}

这更好地表达了您的意图“我想根据 x 上的简单选择执行这些分支中的一个,如果 x 则使用“默认”分支不是任何已知值。”

关于c# - 从另一个类调用方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33693791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com