gpt4 book ai didi

java - "Constructor cannot be applied to given types"错误

转载 作者:行者123 更新时间:2023-12-01 11:57:37 25 4
gpt4 key购买 nike

我不断收到错误:

3 errors found:
File: C:\Users\TUFRob\Documents\Computer Science II\Retail\RetailItemDemo.java [line: 6]
Error: constructor RetailItem in class RetailItem cannot be applied to given types;
required: int,double,java.lang.String
found: no arguments
reason: actual and formal argument lists differ in length
File: C:\Users\TUFRob\Documents\Computer Science II\Retail\RetailItemDemo.java [line: 7]
Error: constructor RetailItem in class RetailItem cannot be applied to given types;
required: int,double,java.lang.String
found: java.lang.String,int,double
reason: actual argument java.lang.String cannot be converted to int by method invocation conversion
File: C:\Users\TUFRob\Documents\Computer Science II\Retail\RetailItemDemo.java [line: 8]
Error: constructor RetailItem in class RetailItem cannot be applied to given types;
required: int,double,java.lang.String
found: no arguments
reason: actual and formal argument lists differ in length

当我尝试运行我的 java 程序时:

public class RetailItemDemo
{
public static void main(String[]args)
{
RetailItem item1 = new RetailItem();
RetailItem item2 = new RetailItem("Designer Jeans", 40, 34.95);
RetailItem item3 = new RetailItem();
}
}

对于这个类:

public class RetailItem
{
private String description;
private int unitsOnHand;
private double price;

public RetailItem(int unitsOnHand, double price, String description)
{
this.unitsOnHand = unitsOnHand;
this.price = price;
this.description = description;
}
}

我无法确定可能导致该错误的原因

最佳答案

RetailItem 的构造函数具有 int、double 和 string 等输入参数。您应该按照参数值的定义顺序传递参数值。否则会给出编译时错误。在这里你犯了同样的错误。

问题 1:

RetailItem item2 = new RetailItem(40, 34.95, "Designer Jeans");

而不是

RetailItem item2 = new RetailItem("Designer Jeans", 40, 34.95);

问题2:

RetailItem item3 = new RetailItem();

此语法将尝试调用默认构造函数。在 RetailItem 类中,您没有定义默认构造函数,因为它也会给出编译时错误。默认构造函数只有在没有定义其他构造函数时才存在默认值,否则您必须手动定义它。

引用:what is constructor in java?

关于java - "Constructor cannot be applied to given types"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28312873/

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