Я сделал метод, который находит значение в моем ArrayList. Я также скопировал этот метод, чтобы использовать его для своего массива, но некоторые вещи, такие как get и size, не работают. Я не знаю, как я должен реструктурировать его.
public Product findProduct(String givenProduct) throws IllegalProductCodeException {
IllegalProductCodeException notFoundMessage
= new IllegalProductCodeException("Product was not found");
int size = rangeOfProducts.length;
int i = 0;
boolean productFound = false;
while (!productFound && i < size) { //While book hasn't been found and i is less than the size of the array
productFound = rangeOfProducts.get(i).getProductCode().equals(givenProduct);
//Checks whether the given value in the array reference is equal to the given reference entered
i++; //if not then add 1
}
if (productFound) {
return rangeOfProducts.get(i - 1);
} else {
throw notFoundMessage;
}
}
Массив, альтернативный .get(i)
будет [i]
а альтернатива .size()
будет .length
.
for (Product product : products) {
if (product.getProductCode().equals(givenProduct)) {
return product;
}
}
throw new IllegalProductCodeException("Product was not found");
Изменить: Java 5, усиленный для цикла, эквивалентен
for (Iterator<Product> iter=products.iterator(); iter.hasNext(); ) {
Product product = iter.next();