【问题标题】:How to fix "constructor in class Rectangle cannot be applied to given types" error in Java?如何修复 Java 中的“类 Rectangle 中的构造函数不能应用于给定类型”错误?
【发布时间】:2019-03-30 03:45:07
【问题描述】:

我是 Java 新手,在尝试编译我的代码时不断收到此编译错误:

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

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

这是我的代码:

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 返回类型。当你给它一个返回类型时,它只是一个与类同名的方法
  • 您还需要将类 Rectangle 的“构造函数”重命名为 Rectangle。而且不要colorstatic!

标签: java


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多