• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception in thread "main" java.lang.NullPointerException error

 
Kevin Quarles
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am getting the following error that I can not figure out, or do not have any idea where to begin. It compiles, but when I go to run it, I get this:
Car

null

null

null

null

null

Exception in thread "main" java.lang.NullPointerException
at Inventory.value(Inventory.java:28)
at Inventory.view(Inventory.java:37)
at Inventory6.<init>(Inventory6.java:35)
at Inventory6.main(Inventory6.java:180)


Here are the codes in question:



and:

 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So basically when you create your Inventory6, you add the SUVs, print them out, and they're null already?

I mean, are those the print statements you're showing us? Does it do the same thing if the call to sort() is removed?
 
Kevin Quarles
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it is doing the same thing
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to consider using more standard naming conventions for class properties, or at least their accessors.

Take a close look at Inventory.add(SUV p).
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(And why is there an add for Cars, and an add for SUVs?)
 
Rob Spoor
Sheriff
Pie
Posts: 20559
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you create your Inventory instance, its products array contains all null values. In the add method you increase numCar, but in several of the loops you are looping over all elements, not just until numCars. As such, you will encounter null for those elements not yet assigned.

Either loop to numCars (exclusively), or use a List<Car> instead.
 
Kevin Quarles
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I apologize for wasting your time. I found what I did wrong, and it had nothing to do with the errors I spoke of above. The problem was in the other classes, and after sleeping on it, I immediately saw what I did wrong.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Um... the add(SUV) is most definitely wrong, and fixing it fixes the output.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic