C#大学课程(第五版)课后习题10.3矩形类

/*10.3
(矩形类)创建一个Rectangle 类。这个类具有属性lengh 和width,默认值都为1。e 还包含readonly 属性Perimeter( 周长)和Area( 面积)。应当通过set 方法验证length 和width都为大于0.0且小于20.0 的浮点数。编写一个程序,测试这个Rectangle 类。
*/
using System;
public class Rectangle
{
private double length;
private double width;

public Rectangle()
{
Length = 1.0;
Width = 1.0;
}
public Rectangle( double theLength, double theWidth )
{
Length = theLength;
Width = theWidth;
}
public double Length
{
get
{
return length;
}
set
{
if ( value > 0.0 && value < 20.0 )
length = value;
else
throw new ArgumentOutOfRangeException( "length", value,
"length must be greater than 0 and less than 20" );
}
}
public double Width
{
get
{
return width;
}
set
{
if (value > 0.0 && value < 20.0)
width = value;
else
throw new ArgumentOutOfRangeException("width", value,
"width must be greater than 0 and less than 20");
}
}
public double Perimeter
{
get
{
return 2 * Length + 2 * Width;
}
}
public double Area
{
get
{
return Length * Width;
}
}
public override string ToString()
{
return string.Format( "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}",
"Length", Length, "Width", Width,
"Perimeter", Perimeter, "Area", Area );
}
}

using System;

public class RectangleTest
{
public static void Main( string[] args )
{
Rectangle rectangle = new Rectangle();

int choice = GetMenuChoice();

while ( choice != 3 )
{
try
{
switch (choice)
{
case 1:
Console.Write( "Enter length: " );
rectangle.Length = Convert.ToDouble( Console.ReadLine() );
break;
case 2:
Console.Write( "Enter width: " );
rectangle.Width = Convert.ToDouble( Console.ReadLine() );
break;
}
Console.WriteLine(rectangle.ToString());
}
catch ( ArgumentOutOfRangeException ex )
{
Console.WriteLine( ex.Message );
}
Console.WriteLine();
choice = GetMenuChoice();
}
}
private static int GetMenuChoice()
{
Console.WriteLine( "1. Set Length" );
Console.WriteLine( "2. Set Width" );
Console.WriteLine( "3. Exit" );
Console.Write( "Choice: " );
return Convert.ToInt32( Console.ReadLine() );
}
}

posted @ 2018-04-07 18:29  v123ve  阅读(314)  评论(0)    收藏  举报