我有工作代码,set和get应该不允许负输入。但是,当它运行时,负输入仍然返回结果,我错过了什么导致负值仍然被计算?另外,我将如何引入允许用户计算多个圆的函数?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace console
{
class Program
{
static void Main(string[] args)
{
Console.Write("What is the circle’s radius: ");
double radius = Convert.ToDouble(Console.ReadLine());
Circle ans = new Circle(radius);
Console.WriteLine("The area of the circle is " + ans.getArea);
Console.WriteLine("The Diameter of the circle is " + ans.getDiameter);
Console.WriteLine("The Circumference of the circle is " + ans.getCircumference);
Console.Write("Enter any character to quit program. ");
double stop = Console.Read();
}
}
}
这就是方法和类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace console
{
class Circle
{
public double radius;
public const double PI = 3.14159;
public Circle(double r)
{
radius = r;
}
public Circle()
{
radius = 0.0;
}
public double getDiameter
{
get
{
return radius * 2;
}
}
public double getArea
{
get
{
return PI * radius * radius;
}
}
public double getCircumference
{
get
{
return 2 * PI * radius;
}
}
// property Radius
public double Radius
{
get
{
return radius;
}
set
{
// ensure non-negative radius value
if (value >= 0)
radius = value;
}
}
}
}
在构造函数中,您正在更改public
字段的值而不是property
,因此永远不会执行setter
方法。我认为你应该让你的字段private
,然后像这样改变你的构造函数:
private double radius;
public Circle(double r)
{
Radius = r;
}
此外,当用户尝试将负值分配给 radius
时,您可能希望在 setter 方法中显示消息或引发异常。
另外,我将如何引入允许用户计算多个圆的函数?
您可以使用loop
。将代码放入循环中并声明计数器。
for(int i = 0; i <= 5; i++)
{
/* put your code here, get the input perform the calculation
and display the message */
}
另一种方式可能是使用while
循环:
while(true)
{
/* put your code here */
Console.WriteLine("Would you like to continue ? (y/n)");
var userChoice = Console.ReadKey().KeyChar;
if(char.ToLower(userChoice) != 'y') break;
}