0

I have an array, moviearray, with logical size of 15 and physical size of 50. I have the following code:

    for(int a=0;a<moviearray.length;a++)
            {
                if (moviearray[a]!=null)
                    {
                        if(moviearray[a].getTitle()==catAddTitle.getText())
                        {
                            moviearray[a].addExisting(Integer.parseInt(catAddNumber.getText()));
                            break;
                        }
                    }   
                else
                {
                    moviearray[a].setTitle(catAddTitle.getText());
                    moviearray[a].setNumber(Integer.parseInt(catAddNumber.getText()));
                    moviearray[a].setGenre(catAddGenre.getText());
                    moviearray[a].setYear(Integer.parseInt(catAddYear.getText()));
                    moviearray[a].setRating(catAddRating.getSelectedItem());
                    moviearray[a].setPrice(Double.parseDouble(catAddPrice.getText()));
                    break;
                }
            }

I am trying to have it so where when I enter a movie title into catAddTitle (text field), and it matches a movie currently in moviearray, it will increase the movie's amount element by the number entered in the textfield catAddNumber. However, when I try doing this, it gives me a nullpointerexception on the line:

    moviearray[a].setTitle(catAddTitle.getText()); 

Example: one of my objects in the array has the elements "Hobbit/55/Adventure/2012/PG-13/10.00" (title, number, genre, year, rating, price). What should happen is that when I enter "Hobbit" into catAddTitle and "3" into catAddNumber, it should change the number to "58" (despite the other textfield data). Thanks in Advance

2
  • By the way you should use .equals() to compare string rather than ==. The later will return false for two distinct instances of Strings with the same content whereas .equals() checks the content. Commented Mar 7, 2014 at 15:14
  • @Pierre I didn't notice that, but I fixed it. Thanks Commented Mar 7, 2014 at 15:32

2 Answers 2

4

In your else-branch - which is executed only if moviearray[a] == null - you need to do

moviearray[a] = new YourObject();

first, i.e. create an instance of your class and store it in the array.

Sign up to request clarification or add additional context in comments.

1 Comment

That fixed it. I keep forgetting that it doesn't automatically make empty objects. Thank you :).
1

You need to compare the String with equals() not with == Operator

change this line with

if(moviearray[a].getTitle()==catAddTitle.getText())

to

if(moviearray[a].getTitle().equals(catAddTitle.getText()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.