[英]Java: Can't add an int to an arraylist
I've created an empty arraylist here: 我在这里创建了一个空的arraylist:
private ArrayList<OrderItem> conveyorBelt = new ArrayList<OrderItem>(10);
And in the same class, I've created a method where I add item into the conveyorBelt by inputting the orderNum (which is an int). 在同一个类中,我创建了一个方法,通过输入orderNum(它是一个int)将项目添加到传送带中。 This is what the method looks like:
该方法如下所示:
public void addToConveyorBelt( int orderNum )
{
OrderItem oi;
conveyorBelt.add(oi.getOrderNum(orderNum)); // line 4
}
This doesn't work. 这行不通。 I get a compile error on line 4, saying this: http://i52.tinypic.com/ny8n86.jpg
我在第4行收到一个编译错误,它是这样的: http : //i52.tinypic.com/ny8n86.jpg
Anyone know where i'm going wrong with this? 有人知道我要怎么做吗?
ps - the OrderItem contains one variable called theOrderNum and a method that calls it called getOrderNum. ps-OrderItem包含一个名为theOrderNum的变量和一个称为getOrderNum的方法。
According to the error message, the method signature of "getOrderNo" does not accept a parameter of type "int". 根据错误消息,方法签名“ getOrderNo”不接受类型为“ int”的参数。 From what you've given, I suspect the OrderItem class looks something like this:
根据您提供的信息,我怀疑OrderItem类看起来像这样:
public class OrderItem {
private int theOrderNum;
OrderItem(int num) {
theOrderNum = num;
}
public int getOrderNum() {
return theOrderNum;
}
}
If so, you want to create a new OrderItem from the orderNum parameter, and then add it to conveyerBelt: 如果是这样,您想从orderNum参数创建一个新的OrderItem,然后将其添加到veyerBelt:
public void addToConveyorBelt(int orderNum) {
OrderItem oi = new OrderItem(orderNum);
conveyorBelt.add(oi);
}
If not, you need to update the question to include more information about the OrderItem class. 如果不是,则需要更新问题以包括有关OrderItem类的更多信息。
getOrderNum obviously returns an int. getOrderNum显然返回一个int。 Your arraylist is an arraylist of
OrderItems
. 您的arraylist是
OrderItems
的arraylist。 What are you expecting to happen? 您期望发生什么?
Not only that, but you're guarunteed a null pointer exception there because oi
isn't initialised. 不仅如此,而且由于
oi
尚未初始化,因此您在该处被确保为空指针异常。
I suspect your method should be something like this: 我怀疑您的方法应该是这样的:
public void addToConveyorBelt(int orderNum){
OrderItem oi = getOrderItem(orderNum);
conveyorBelt.add(oi);
}
you define arraylist like that 你像这样定义arraylist
private ArrayList<OrderItem> conveyorBelt = new ArrayList<OrderItem>(10);
It means you can only add OrderItem
to the list 这意味着您只能将
OrderItem
添加到列表中
public void addToConveyorBelt( int orderNum )
{
OrderItem oi;
conveyorBelt.add(oi.getOrderNum(orderNum)); // here it fails
}
Change it as follows 如下更改
public void addToConveyorBelt( int orderNum )
{
OrderItem oi = new OrderItem(orderNum);
conveyorBelt.add(oi); // here it fails
}
oi.getOrderNum(orderNum)
should throw NullPointerException oi.getOrderNum(orderNum)
应该抛出NullPointerException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.