1、按以下要求编写程序
(1) 创建一个Rectangle类,添加width和height两个成员变量;
(2) 在Rectangle中添加两种方法分别计算矩形的周长和面积;
(3) 编程利用Rectangle输出一个矩形的周长和面积(长和宽由用户从键盘输入);
import java.util.Scanner;
public class Rectangle {
private double width;
private double height;
public void setWidth(double width) {
this.width = width;
}
public void setHeight(double height) {
this.height = height;
}
public double calculatePerimeter() {
return 2 * (width + height);
}
public double calculateArea() {
return width * height;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Rectangle rectangle = new Rectangle();
System.out.print("请输入矩形的宽度:");
double width = scanner.nextDouble();
rectangle.setWidth(width);
System.out.print("请输入矩形的高度:");
double height = scanner.nextDouble();
rectangle.setHeight(height);
System.out.println("矩形的周长为:" + rectangle.calculatePerimeter());
System.out.println("矩形的面积为:" + rectangle.calculateArea());
}
}
2、按以下要求编写程序
(1) 编写Animal接口,接口中声明run() 方法;
(2) 定义Bird类和Fish类实现Animal接口;
(3) 编写Bird类和Fish类的测试程序,并调用其中的run()方法;
// Animal接口
interface Animal {
void run();
}
// Bird类实现Animal接口
class Bird implements Animal {
@Override
public void run() {
System.out.println("鸟儿在天空飞翔。");
}
}
// Fish类实现Animal接口
class Fish implements Animal {
@Override
public void run() {
System.out.println("鱼儿在水中游动。");
}
}
// 测试程序
public class Main {
public static void main(String[] args) {
Bird bird = new Bird();
Fish fish = new Fish();
bird.run();
fish.run();
}
}