我一直在收到错误:
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;
}
}
我无法查看可能导致错误的原因
答案 0 :(得分:1)
RetailItem的构造函数有输入参数,如int,double和string。您应该根据它的定义按顺序传递参数值。否则它会给compile time error
。在这里你犯了同样的错误。
问题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
类中,您没有定义默认构造函数,因为它也会给出compile time error
。默认构造函数仅在没有定义其他构造函数时才存在,否则您必须手动定义它。
答案 1 :(得分:0)
您的RetailItem
只有一个构造函数:
public RetailItem(int unitsOnHand, double price, String description){...}
然后,你的所有电话都错了:
//Problem 1: wrong because you have no constructor with no param
RetailItem item1 = new RetailItem();
RetailItem item3 = new RetailItem();
和
// Problem 2:
RetailItem item2 = new RetailItem("Designer Jeans", 40, 34.95);
//wrong because your Constructor is RetailItem(int, double, String)
// not RetailItem(String, int, double)
如何解决:
在您的课程中添加默认的Constrcutor(无参数)以解决问题1
public RetailItem(){
}
要解决问题2,请将第11行更改为:
RetailItem item2 = new RetailItem( 40, 34.95,"Designer Jeans");