gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:57 28 4
gpt4 key购买 nike

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

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

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

这是我的代码:

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
}
}

关于java - 如何修复Java中的 "constructor in class Rectangle cannot be applied to given types"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55427941/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com