Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

WHat is Exception in thread "main" java.lang.NullPointerException ?  RSS feed

 
Raghu Tiwari
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote the following code from Head FIrst java book..
and i got this error saying..
Exception in thread "main" java.lang.NullPointerException
at Puzzle4.main(Puzzle4.java:18)
..which is at the line 18 : result = result + obs[x].doStuff(x);
Please tell me whats wrong?
---------------------------------------------------------------------------




----------------------------------------------------------
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That means that obs[x] is null.

The mistake is in line 8: while (x>6) {

Can you see what you did wrong there? Hint: What is the value of x when the program reaches line 8, and what happens then?
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37242
519
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you explain what this does?


How many times does the loop run? (Hint: it doesn't run 6 times)
 
Vijay Vishwa
Ranch Hand
Posts: 40
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While loop not execute for even single iteration


try changing loop condition to
 
Norm Radder
Ranch Foreman
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exception in thread "main" java.lang.NullPointerException
at Puzzle4.main(Puzzle4.java:18)
..which is at the line 18 : result = result + obs[x].doStuff(x); 

The contents of the variable: obs[x] is null.

To see what is in the obs array add this statement in the code after where you think the obs array has been filled:
The print out will show you what elements in obs have null values.

Then you need to fix the code so that there aren't any null elements.
 
Campbell Ritchie
Marshal
Posts: 55751
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And I thought that code could never throw an Exception. Read it very carefully and look very carefully at your line 8 in the second class. See if you can see a difference from the original. Then see if you can see the difference without reading everybody else's replies who were quicker than me

And welcome to the Ranch
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!