题目一
1、创建一个名为Circle的类,半径为r,此类有2个构造方法,一个默认的无参构造方法;一个有参构造方法,参数为r。包含3个实例函数:
(1)double getR():获得半径r的值。
(2)double getArea():获得圆的面积。
(3)void setR(double r):设置半径r的值。
并编写类TestCircle测试Circle类。
代码:
public class Circle {
double r;
public Circle() {
}
public Circle(double r) {
this.r = r;
}
public double getR() {
return r;
}
public double getArea() {
return r * r * Math.PI;
}
public void setR(double r) {
this.r = r;
}
}
import java.util.Scanner;
public class TestCircle {
public static void main(String[] args) {
Circle circle12 = new Circle(4);
myPrint(circle12.getR(),circle12.getArea());
Circle circle = new Circle();
Scanner scanner = new Scanner(System.in);
System.out.print("请输入圆的半径:");
double r = scanner.nextDouble();
circle.setR(r);
myPrint(circle.getR(),circle.getArea());
}
public static void myPrint(double r,double result){
System.out.println("圆的半径为" +r);
System.out.println("圆的面积为" + result);
}
}
运行结果截图:
题目二
2、创建一个名为Triangle的类,三个边为a,b,c,此类有2个构造方法,一个默认的无参构造方法;一个有参构造方法,参数为a,b,c。包含3个实例函数:
(1)double[] getABC():获得三个边的值。
(2)double getArea():获得三角形的面积。
(3)void setABC(double a, double b, double c):设置三个边的值。
并编写类TestTriangle测试Triangle类。
代码:
public class Triangle {
double a;
double b;
double c;
public Triangle() {
}
public Triangle(double a, double b, double c) {
if ((a + b > c) && (a + c > b) && (b + c > a)) {
this.a = a;
this.b = b;
this.c = c;
}else{
System.out.println("对不起,无法构成三角形!");
}
}
double[] getABC() {
return new double[]{a, b, c};
}
double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt((p * (p - a)) * (p - b) * (p - c));
}
void setABC(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public class TestTriangle {
public static void main(String[] args) {
Triangle t1 = new Triangle();
t1.setABC(6, 8, 10);
System.out.print("三角形的三边长分别为:");
for (double x:t1.getABC()
) {
System.out.print(x+" ");
}
System.out.println();
System.out.println("三角形的面积为" + t1.getArea());
Triangle t2 = new Triangle(6, 3, 12);
}
}
运行结果截图:
题目三
3、创建一个名为RecTangle的类,高和宽分别为h,w,此类有2个构造方法,一个默认的无参构造方法;一个有参构造方法,参数为h,w。包含3个实例函数:
(1)double[] getHW():获得高和宽的值。
(2)double getArea():获得矩形的面积。
(3) 设置高和宽的值。
代码:
public class RecTangle {
double h;
double w;
public RecTangle() {
}
public RecTangle(double h, double w) {
this.h = h;
this.w = w;
}
double[] getHW() {
return new double[]{h, w};
}
double getArea() {
return h * w;
}
}
public class TestRecTangle {
public static void main(String[] args) {
RecTangle r1 = new RecTangle(4,2);
System.out.print("矩形的长和宽分别为");
for (double x: r1.getHW()
) {
System.out.print(x +" ");
}
System.out.println();
System.out.println("矩形的面积为"+r1.getArea());
}
}
运行结果截图: