-3

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.

fmatt
  • 464
  • 1
  • 5
  • 15
TheKingSid
  • 39
  • 6
  • See [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jarmod Mar 30 '21 at 17:15

2 Answers2

0

You're getting a null pointer here not for the fact that there is an error assigning the pointer, but rather you are looking to compare the pointer values of the string rather than their contents. To assess equality based on contents, use the .equals function between the two strings.

Nicholas Dullam
  • 291
  • 1
  • 9
0

I think you should put break inside the if statement. Otherwise it will always stop the loop after checking the first element and if first element doesn't match the condition, nothing is assigned to p and it will be null.

Also as jarmod said, String comparison must be done by .equals() method. So you must have something like this:

    @Override
    public String execute(VendingMachine v, String userinput){
       Product p
       for( Product i : v.getProducts()){
            if(i.getName().equals(userinput)) {
                p=i;
                break;
            }
        }}
fmatt
  • 464
  • 1
  • 5
  • 15