常量与变量的声明与使用

1. 单击File|New|Java Project命令,打开New Java Project对话框。在Project name文本框中输入MyProject2,单击Finish按钮关闭对话框。

2. 单击File|New|Class命令,打开New Java Class的对话框,在Name文本框中输入AreaAndLength,然后选中public static void main(String[] args)Generate comments复选框以自动产生main主方法及程序的相关注释,最后单击Finish按钮。

3. 在代码编辑器中输入以下代码

public class AreaAndLength {



	/**

	 * @param args

	 */

	public static void main(String[] args) {

		// TODO Auto-generated method stub

		double length,area;

		Circle circle=null;

		Triangle triangle;

		Ladder ladder;

		circle=new Circle(6);

		triangle=new Triangle(3,4,5);

		ladder=new Ladder(3,4,5);

		length=circle.getLength();

		System.out.println("圆的周长:"+length);

		area=circle.getArea();

		System.out.println("圆的面积:"+area);

		length=triangle.getLength();

		System.out.println("三角形的周长:"+length);

		area=triangle.getArea();

		System.out.println("三角形的面积:"+area);

		area=ladder.getArea();

		System.out.println("梯形的面积:"+area);

		triangle.setABC(12.0,34.0,1.0);

		area=triangle.getArea();

		System.out.println("三角形的面积:"+area);

		length=triangle.getLength();

		System.out.println("三角形的周长:"+length);



	}



}

class Triangle{

	double sideA,sideB,sideC,area,length;

	boolean boo;

	public Triangle(double a,double b,double c){

		sideA=a;

		sideB=b;

		sideC=c;

		if(a+b>c&&a+c>b&&b+c>a&&a-b<c&&a-c<b&&b-a<c&&b-c<a&&c-a<b&&c-b<a)

		{

			boo=true;

		}

		else

		{

			boo=false;

		}

	}

	double getLength()

	{

		length=sideA+sideB+sideC;

		return length;

	}

	public double getArea(){

		if(boo)

		{

			double p=(sideA+sideB+sideC)/2.0;

			area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));

			return area;

		}

		else

		{

			System.out.println("不是一个三角形,不能计算面积");

			return 0;

		}

	}

	public void setABC(double a,double b,double c){

		sideA=a;

		sideB=b;

		sideC=c;

	}

}

class Ladder{

	double above,bottom,height,area;

	Ladder(double a,double b,double h)

	{

		above=a;

		bottom=b;

		height=h;

	}

	double getArea()

	{

		area=(above+bottom)*height/2;

		return area;

	}

}

class Circle{

	double radius,area,length;

	Circle(double r){

		radius=r;

	}

	double getArea(){

		area=3.14159265*radius*radius;

		return area;

	}

	double getLength(){

		length=2*3.14159265*radius;

		return length;

	}

	void setRadius(double newRadius){

		radius=newRadius;

	}

	double getRadius(){

		return radius;

	}

}

 

4. 调试并运行程序。

你可能感兴趣的:(变量)