I need help with a method using a for-loop
public void collect( int ordNum )
{
Basket b = new Basket(ordNum);
for (Basket b : conveyerBelt) { // line 4
readyCollected.add(b);
}
}
What I'm trying to do with this method开发者_JAVA技巧 is search through an ArrayList for a orderNum. When I find it, I want to add the orderNum i entered in to the readyCollected. Problem: I get an error message on line 4.
Was wondering if you can guys can help me implement this method.
BTW, the conveyerBelt already contains Basket with an order number. So lets say the conveyerBelt contains Basket with order number 3, and I enter in 3, I want it to add Basket to Arraylist readyCollected containing order number 3.
I'm guessing your error is that conveyerBelt is not Iterable. To use the foreach construct, you must make sure the object you are Iterating over implements Iterable.
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2
Excerpt:
The Expression must either have type Iterable or else it must be of an array type (§10.1), or a compile-time error occurs.
The scope of a local variable declared in the FormalParameter part of an enhanced for statement (§14.14) is the contained Statement
The meaning of the enhanced for statement is given by translation into a basic for statement.
If the type of Expression is a subtype of Iterable
, then let I be the type of the expression Expression.iterator()
. The enhanced for statement is equivalent to a basic for statement of the form:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableModifiersopt Type Identifier = #i.next();
Statement
}
You don't give nearly enough information to solve this properly.
- What is the error?
- What types are conveyerBelt and readyCollected?
Also what do you mean by "order number" - the Nth item in the list or is it some field?
conveyerBelt
should be declared as Collection<Basket >
By Collection
I meant any Collection
Is it a compile error? Maybe something about a symbol and conveyerBelt
? Because it's not defined in the snippet you've given us.
You are using the same name (b) for two variables. That's probably the cause of the error you get, but I am not sure what you are trying to achieve with that code.
I think it's something like
public void collect( int ordNum )
{
for (Basket b : conveyerBelt) {
if (b.getOrdNum() == ordNum) {
readyCollected.add(b);
return; // if only one occurrence wanted
}
}
}
assuming conveyerBelt
is some Collection of Basket
and readyCollected
is some List of Basket
.
精彩评论