This content has been marked as final. Show 3 replies
james1232 wrote:NullPointerException (sometimes abbreviated as NPE) means that your code has a reference value that is null, and the code is trying to use that value as if it was referring to an object. For example, if you had a String b = null and you tried to do "char c = b.charAt(1);" you would get a NPE. Makes sense, right?
Hello everyone, maybe someone can figure this one out.
Here is a sample of the output:
How old are you? 22
Have a coupon? (Y/N)
Exception in thread "main" java.lang.NullPointerException
The error message tells you that this occurred in the NicePrice.java source code file, on line number 16. I believe this is line number 16.
In this line, myScanner is a variable whose value might be null, but your code uses this variable successfully so it is very likely not null.
reply = myScanner.findInLine(".").charAt(0);
Next, what does findInLine() return? Go to the API docs [http://java.sun.com/javase/6/docs/api/], find and select the Scanner class. Then scroll down to the findInLine() method that takes a String as an argument and select it [http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#findInLine(java.lang.String)] Here you find that this method behaves like the findInLine() method that takes a Pattern. That method is just below this one.
Reading the description of findInLine(Pattern pattern), you will note that this method can return null. Maybe that's what happening. You can test this hypothesis easily by putting in a line of code right before the current line number 16
If that line shows 'null' right before the NPE is thrown, now you know the reason why NPE is thrown. You will still need to find out why findInLine is returning null.
change reply = myScanner.findInLine(".").charAt(0); to reply = myScanner.next(".").charAt(0);
I have same problem but it's working when I change to next.
I have the same problem with James... I have "Java for Dummies" book and the code given by James is what is exactly on the book. I tried to run the program and it doesn't work. I spent 2 and a half hours for this problem. There's no red line indicating I have the error in the code. I can enter the age but the problem is with the the "reply = myScanner.findInLine(".").charAt(0);" part. I can't move to the next page because I'm not yet done with this problem. I tried to search to solve this problem and most of the people especially those Java geeks talk nonsense...
But Nickson, you save me!!!!!!!!! If you were here I might have kissed you! Thanks for sharing your knowledge. Keep on sharing... thanks a lot!
I think Barry Burd, author of "Beginning Programming with Java" 2nd edition should revised his book so that beginners like me will not be confused and will not waste so much time thinking about what went wrong on the code. The code in page 164 doesn't work!
Edited by: sweet_mika on Sep 16, 2010 12:03 PM