2022-06-30 22:53:51 +02:00

86 lines
2.2 KiB
C#

namespace Homework3
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter the radius of a sphere");
int radius = 0;
bool validInput = false;
while (!validInput)
{
var input = Console.ReadLine();
try
{
radius = int.Parse(input);
validInput = true;
}
catch
{
Console.WriteLine("Input could not be parsed as a double, try again!");
}
}
var sphere = new Sphere(radius);
Console.WriteLine("The volume of the sphere is {0}", sphere.volume());
Console.WriteLine("The area of the sphere is {0}", sphere.area());
Console.WriteLine("Now enter a new radius for the same sphere");
validInput = false;
while (!validInput)
{
var input = Console.ReadLine();
try
{
radius = int.Parse(input);
validInput = true;
}
catch
{
Console.WriteLine("Input could not be parsed as a double, try again!");
}
}
// Radius changed!
sphere.Radius = radius;
Console.WriteLine("The volume of the sphere is now {0}", sphere.volume());
Console.WriteLine("The area of the sphere is now {0}", sphere.area());
}
}
internal class Sphere
{
private int _radius = 0;
public Sphere() { }
public Sphere(int radius)
{
_radius = radius;
}
public int Radius
{
set
{
if (value >= 0)
_radius = value;
else
_radius = 0;
//_radius = Math.Max(0, value);
}
}
public double volume()
{
return (4.0 / 3.0) * Math.PI * Math.Pow(_radius, 3);
}
public double area()
{
return 4.0 * Math.PI * Math.Pow(_radius, 2);
}
}
}