Java 向Arraylist添加项
因此,我尝试将项目添加到arraylist中,但是当我尝试编写add方法时,IDE给了我一个错误,我传递的“name、cusip和ticker”错误。有人能解释一下我在这里做错了什么吗?提前谢谢 这是我的ETF课程Java 向Arraylist添加项,java,arraylist,Java,Arraylist,因此,我尝试将项目添加到arraylist中,但是当我尝试编写add方法时,IDE给了我一个错误,我传递的“name、cusip和ticker”错误。有人能解释一下我在这里做错了什么吗?提前谢谢 这是我的ETF课程 package fundProject; import java.util.Scanner; public class ETF extends AbstractETF { private String name; private int cusip; p
package fundProject;
import java.util.Scanner;
public class ETF extends AbstractETF {
private String name;
private int cusip;
private int ticker;
public ETF(String name, int cusip, int ticker) {
this.name = getName();
this.cusip = getCusip();
this.ticker = getTicker();
}
public int getCusip() {
System.out.println("Please enter the Cusip of the ETF");
Scanner sc = new Scanner(System.in);
cusip = sc.nextInt();
return cusip;
}
public int getTicker() {
System.out.println("Please enter the Ticker of the ETF");
Scanner sc = new Scanner(System.in);
ticker = sc.nextInt();
return ticker;
}
public String getName() {
System.out.println("Please enter the Name of the ETF");
Scanner sc = new Scanner(System.in);
name = sc.next();
return name;
}
}
这是我的主要课程
package fundProject;
import java.util.ArrayList;
public class mainClass {
public static void main(String[] args) {
ArrayList<ETF> etfArrayList = new ArrayList<ETF>();
etfArrayList.add(new ETF(name, cusip, ticker));
}
}
package项目;
导入java.util.ArrayList;
公共类主类{
公共静态void main(字符串[]args){
ArrayList etfArrayList=新的ArrayList();
新增(新ETF(名称、cusip、股票代码));
}
}
这是因为您没有准确定义名称
cusip
和股票代码
是什么。您应该首先在某个地方声明它们
例如:
public static void main(String[] args) {
ArrayList<ETF> etfArrayList = new ArrayList<ETF>();
String name = "John Doe";
int cusip = 1;
int ticker = 1;
etfArrayList.add(new ETF(name, cusip, ticker));
}
}
总体而言,您的ETF类可以使用另一个检查。这不容易理解。首先,您没有在
mainClass
类中定义变量name
、cusip
和ticker
,因此编译器在此处生成错误
然而,您甚至不在ETF
构造函数中使用这3个参数
我会做以下事情之一:
- 删除构造函数的参数,不要向构造函数传递任何内容
- 或者,将代码移动到
,请求用户输入,这样您就可以将这些变量传递到构造函数中。构造函数只需复制这些值main
ETF
类非常混乱。首先它调用。然后,每当有人试图使用它作为变量时,它就会尝试从扫描仪中读取新值。我会认真重新考虑你的设计。还有。
public ETF(String name, int cusip, int ticker) {
this.name = name;
this.cusip = cusip;
this.ticker = ticker;
}