程序填空题:
编写长方形类,计算面积及周长。创建两个对象,输出它们的面积及周长。
public class Rectangle
{
private int width;//字段,宽,类中的变量,分配内存
private int height;//字段,高
public 【1】 Width //属性,可读可写属性
{
get { return width; }
set
{
if (value >= 0)
{
width = 【2】 ;
}
else
{
throw new Exception("宽不能小于0");
}
}
}
public 【3】 Height//属性
{
get { return height; }
set
{
if (value >= 0)
{
height = 【4】 ;
}
else
{
throw new Exception("高不能小于0");
//Exception ex= new Exception("高不能小于0");
//throw ex;
}
}
}
public Rectangle()
{
width = 0;
height = 0;
}
public Rectangle (int width,int height)
{
this.Width = 【5】 ;
this.Height = 【6】 ;
}
public 【7】 Area()//方法,计算面积
{
return width * height;
}
public 【8】 Perimeter()
{
return 2 * (width + height);
}
}
class Program//测试类
{
static void Main(string[] args)
{
try
{
//可能出现异常的代码
Rectangle rect1 = new Rectangle();
rect1.Width = 5;
rect1.Height = -4;
Console .WriteLine ("宽为{0}",rect1 .Width );
Console.WriteLine("面积为{0},周长为{1}", rect1.Area(), rect1.Perimeter());
}
catch (Exception 【9】 )
{
Console.WriteLine(ex.Message);
}
try
{
Rectangle rect2 = new Rectangle(-7, 6);
Console.WriteLine("面积为{0},周长为{1}", rect2.Area(), rect2.Perimeter());
}
catch (Exception 【10】 )
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
编写长方形类,计算面积及周长。创建两个对象,输出它们的面积及周长。
public class Rectangle
{
private int width;//字段,宽,类中的变量,分配内存
private int height;//字段,高
public 【1】 Width //属性,可读可写属性
{
get { return width; }
set
{
if (value >= 0)
{
width = 【2】 ;
}
else
{
throw new Exception("宽不能小于0");
}
}
}
public 【3】 Height//属性
{
get { return height; }
set
{
if (value >= 0)
{
height = 【4】 ;
}
else
{
throw new Exception("高不能小于0");
//Exception ex= new Exception("高不能小于0");
//throw ex;
}
}
}
public Rectangle()
{
width = 0;
height = 0;
}
public Rectangle (int width,int height)
{
this.Width = 【5】 ;
this.Height = 【6】 ;
}
public 【7】 Area()//方法,计算面积
{
return width * height;
}
public 【8】 Perimeter()
{
return 2 * (width + height);
}
}
class Program//测试类
{
static void Main(string[] args)
{
try
{
//可能出现异常的代码
Rectangle rect1 = new Rectangle();
rect1.Width = 5;
rect1.Height = -4;
Console .WriteLine ("宽为{0}",rect1 .Width );
Console.WriteLine("面积为{0},周长为{1}", rect1.Area(), rect1.Perimeter());
}
catch (Exception 【9】 )
{
Console.WriteLine(ex.Message);
}
try
{
Rectangle rect2 = new Rectangle(-7, 6);
Console.WriteLine("面积为{0},周长为{1}", rect2.Area(), rect2.Perimeter());
}
catch (Exception 【10】 )
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}