Problem:Cannot call the class parameter inside the for loop statement
Implementation:I need to call this class inorder my rest api list will function and will show all the data.
Problem:Cannot call the class parameter inside the for loop statement
Implementation:I need to call this class inorder my rest api list will function and will show all the data.
//this is working and able to get all the data, which the output is in "cmd"; public void ool8(){ Product pBuilder = Product.newBuilder().build(); ProductList productList = productServiceBlockingStub.findAllRepeated(pBuilder); List<Product> products2 = productList.getProductList(); for (Iterator iterator = products2.iterator(); iterator.hasNext();) { Product product = (Product) iterator.next(); ProductEntity productEntity2 = new ProductEntity( product.getPurchaseItem(), product.getProductname(), product.getProductbrand(), product.getProductprice(), product.getProductdescription(), product.getProductquantity(), product.getProductexpirationdate() ); List<ProductEntity> list = new ArrayList<>(); list.add(productEntity2); System.out.println(list); }
//this is Not working cannot call the "productEntity2" outside the for loop; //I need return in a method List<ProductEntity> for rest api implementation. public List<ProductEntity> ool8(){ List<ProductEntity> list = new ArrayList<>(); Product pBuilder = Product.newBuilder().build(); ProductList productList = productServiceBlockingStub.findAllRepeated(pBuilder); List<Product> products2 = productList.getProductList(); for (Iterator iterator = products2.iterator(); iterator.hasNext();) { Product product = (Product) iterator.next(); ProductEntity productEntity2 = new ProductEntity( product.getPurchaseItem(), product.getProductname(), product.getProductbrand(), product.getProductprice(), product.getProductdescription(), product.getProductquantity(), product.getProductexpirationdate() ); } //this is the issue calling "productEntity2" outside of for loop list.add(productEntity2); System.out.println(list); return list; }
Advertisement
Answer
productEntity2
lives in the scope of the for
loop, you created it there. Hence, you cannot call productEntity2
outside of the loop (its scope). It looks to me that for each product in iterator
, you’d like to add an entity to list
, so the right thing to do is putting list.add(productEntity2);
inside the for loop (at the end, right after creating productEntity2
).