如何修复 Java 中的"constructor in class Rectangle cannot be applied to given types"错误?



我对Java很陌生,在尝试编译代码时不断收到此编译错误:

"MyRectangle.java:3:错误:类矩形中的构造函数矩形不能应用于给定类型; 矩形矩形1 = 新矩形(5.0, 10.0, "红色"(; ^ 必需:无参数 找到:双精度,双精度,字符串 原因:实际参数列表和正式参数列表的长度不同

MyRectangle.java:8:错误:类中的构造函数矩形 矩形不能应用于给定类型; 矩形矩形2 = 新矩形(3.5, 4.3, "黄色"(; ^ 必需:无参数 找到:双精度,双精度,字符串 原因:实际参数列表和正式参数列表的长度不同">

这是我的代码:

public class MyRectangle {
  public static void main (String[] args) {
    Rectangle rectangle1 = new Rectangle(5.0, 10.0, "red");
      System.out.println("The width of the first rectangle is " + 
          rectangle1.getWidth() + 
         " the height is " + rectangle1.getHeight() + " the area is " + 
           rectangle1.findArea() + 
           " and the color is " + rectangle1.getColor());
    Rectangle rectangle2 = new Rectangle(3.5, 4.3, "yellow");
      System.out.println("The width of the second rectangle is " + 
        rectangle2.getWidth() +
        " the height is " + rectangle2.getHeight() + " the area is " + 
          rectangle2.findArea() +
         " and the color is " + rectangle2.getColor());
  }
}
class Rectangle {
  private double width = 1.0;
  private double height = 1.0;
  private static String color = "white";
  public double MyRectangle(){ 
  }
  public double MyRectangle(double widthParam, double heightParam, String 
   colorParam){ 
  }
  public double getWidth(){
    return width;     
    }
  public void setWidth(double widthParam){
    width = widthParam;   
    }
  public double getHeight(){ 
    return height;
    }
  public void setHeight(double heightParam){
    height = heightParam;     
    }
  public String getColor(){
    return color;     
    }  
  public static void setColor(String colorParam){ 
    color = colorParam;
    }
  public double findArea(){ 
   return width * height;
   }
 }

您的错误是您尝试将数据类型(double,int,float等(分配给构造函数。在 Java 中,构造函数仅由类的名称和参数定义。例。

public class MyClass(){
   //My constructor
   public MyClass(){
     //My code
   }
}

相关内容

最新更新