I'm trying to build this class, where Product
is an object, and getProducts
is an ArrayList
of the product object.
Now, in this instance, I'm trying to iterate through the ArrayList to find the product that has the same name as the input (userinput
), and once it finds the same one, I'd tie that product down to a Product p
, in a way like using a pointer.
So in order to do that I set up a new pointer object, Pointer p=null
. I had to initialize it as the subsequent bits require the p.getName
and other methods.
However in doing so, I'm always getting a null pointer exception
. Is there a better way to approach this?
public class purchase implements Command {
@Override
public String execute(VendingMachine v, String userinput){
Product p=null;
for( Product i : v.getProducts()){
if(i.getName().equals(userinput)) {
p=i;
}
break;
EDIT- a couple people had mentioned that I should use .equals()
, and yes I had overlooked this, however, that's not the reason causing the issue here.
Also edited the question to make it more comprehensive.