代码错误import java.util.Scanner; public class Main{ public static void main (String args[]){ Shape s=new Oval(a,b); System.out.println("The area of "+s.toString()+" is "+s.area()); System.out.println("The perimeterof "+s.toString()+" is "+s.perimeter()); }} class Shape{ abstract double area(); abstract double perimeter(); } class Oval extends Shape{ private double a; //长轴半径 private double b; //短轴半径 Oval(double a,double b){ Scanner scanner = new Scanner(System.in); this.a= scanner.nextDouble(); this.b= scanner.nextDouble(); } Oval(){ this.a=0; this.b=0; } double area(){ return Math.PI*a*b; } double perimeter(){ return 2*Math.PI*b+4*(a-b); //L=2πb+4(a-b) } public String toString() { return "Oval(a:" + this.a + ",b:" + this.b + ")"; } }
时间: 2024-01-07 15:03:45 浏览: 139
这段代码有两个问题:
1. 在创建 Oval 对象时,应该将 main 函数中的 a 和 b 作为参数传递进去,而不是从控制台读取输入。因此,Shape s=new Oval(a,b); 应该改为 Shape s=new Oval(3, 4);(3 和 4 可以替换为任意值)
2. 在 Shape 类中的 abstract 方法需要添加 abstract 关键字,因为 Shape 类是一个抽象类。
修改后的代码如下:
```java
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
double a = 3; // 长轴半径
double b = 4; // 短轴半径
Shape s = new Oval(a, b);
System.out.println("The area of " + s.toString() + " is " + s.area());
System.out.println("The perimeter of " + s.toString() + " is " + s.perimeter());
}
}
abstract class Shape {
abstract double area();
abstract double perimeter();
}
class Oval extends Shape {
private double a; // 长轴半径
private double b; // 短轴半径
Oval(double a, double b) {
this.a = a;
this.b = b;
}
Oval() {
this.a = 0;
this.b = 0;
}
double area() {
return Math.PI * a * b;
}
double perimeter() {
return 2 * Math.PI * b + 4 * (a - b); // L=2πb+4(a-b)
}
public String toString() {
return "Oval(a:" + this.a + ",b:" + this.b + ")";
}
}
```
阅读全文