Java程序设计上机操作与习题解析 第二章 实验1
程序员文章站
2022-03-18 13:37:49
...
package chapter2;
public class AreaAndLength {
public static void main(String[] args) {
double length;
double area;
Circle circle=null;
Triangle triangle;
Ladder ladder;
circle=new Circle(2.0);
triangle=newT riangle(3.0,4.0,5.0);
ladder=new Ladder(3.0,5.0,7.0);
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,34, 1);
area=triangle.getArea();
System.out.println("三角形的面积是:"+area);
length=triangle.getLength();
System.out.println("三角形的周长是:"+length);
}
}
package chapter2;
/**
*
*
@author 23820
* 描述三角形
* 具有三边,以及周长、面积
* 功能:返回周长、返回面积、修改三边
* 有一个boolean类型的属性,判断是否可以构成一个三角形
*/
public class Triangle {
double sideA,sideB,sideC,area,length;
boolean boo;
public Triangle(double a,double b,double c) {
this.sideA=a;
this.sideB=b;
this.sideC=c;
if(sideA+sideB>sideC&&sideA+sideC>sideB&&sideB+sideC>sideA) {
this.boo=true;
}
else {
this.boo=false;
}
}
double getLength() {
return this.length=this.sideA+this.sideB+this.sideC;
}
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) {
this.sideA=a;
this.sideB=b;
this.sideC=c;
}
}
package chapter2;
/**
*
*
@author 23820
* 描述梯形
* 上底、下底、高、面积
* 功能:返回面积
*/
public class Ladder {
double above,bottom,height,area;
Ladder(double a,double b,double h){
this.above=a;
this.bottom=b;
this.height=h;
}
double getArea() {
return area=(above+above)*height/2.0;
}
}
package chapter2;
public class DataTypeDemo {
public static void main(String[] args) {
byte b=0x55;
short s=0x55ff;
int i=1000000;
long l=0xffffL;
char c='a';
float f=0.23F; //执行必须有F
double d=0.7E-3;
boolean B=true;
String S="这是字符串数据类型";
System.out.println("字节型变量b="+b);
System.out.println("短整型变量s="+s);
System.out.println("整型变量i="+i);
System.out.println("长整型型变量l="+l);
System.out.println("字符型变量c="+c);
System.out.println("单精度型变量f="+f);
System.out.println("双精度型变量d="+d);
System.out.println("布尔型变量B="+B);
System.out.println("字符串型变量S="+S);
}
}
package chapter2;
/**
*
*
@author 23820
* 描述圆形
* 半径、周长、面积
* 功能:返回周长、面积
*/
public class Circle {
double radius,area;
Circle(double r){
this.radius=r;
}
double getArea() {
return area=Math.PI*radius*radius;
}
double getLength() {
return Math.PI*radius*2.0;
}
void setRadius(double newRadius) {
radius=newRadius;
}
double getRadius() {
return radius;
}
}
下一篇: JS函数的定义及调用