Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

Another noob in trouble! Help me out if you like!

Thread view: 
the_transcriber@yahoo.com - 09 Oct 2007 07:42 GMT
Hello again. This time i have another code that isn't working. It is
like a ticket program... It should ask the user "how old are you?",
following that answer it should say "Have a coupon? (Y/N)"
and then it will give the ticket price based on the answers. When i
run it, here is the output that i recieve...

How old are you? 51
Have a coupon? (Y/N) Exception in thread "main"
java.lang.NullPointerException
   at Discount.main(Discount.java:15)

Process completed.

____________________________________________________________________________

So here is the code... any ideas? Im completely new to this, and this
program should work without using more methods that i haven't learned
yet, it should work the way it is i thought! So if anyone can see what
i did wrong with it using the stuff i have already used, let me know,
thanks! This is from the Beginning Programming with Java for Dummies -
2nd Edition book

import java.util.Scanner;

class Discount {

    public static void main(String args[]) {
        Scanner myScanner = new Scanner(System.in);
        int age;
        double price = 0.00;
        char reply;

        System.out.print("How old are you? ");
        age = myScanner.nextInt();

        System.out.print("Have a coupon? (Y/N) ");
        reply = myScanner.findInLine(".").charAt(0);

        if (age >= 12 && age < 65) {
            price = 9.25;
        }
        if (age < 12 || age >= 65) {
            price = 5.25;
        }

        if (reply == 'Y' || reply == 'y') {
            price -= 2.00;
        }
        if (reply != 'Y' && reply != 'y' &&
            reply!='N' && reply!='n') {
            System.out.println("Huh?");
        }

        System.out.print("Please pay $");
        System.out.print(price);
        System.out.print(". ");
        System.out.println("Enjoy the show!");
    }
}
kcwong - 09 Oct 2007 08:27 GMT
> Hello again. This time i have another code that isn't working. It is
> like a ticket program... It should ask the user "how old are you?",
[quoted text clipped - 6 lines]
> java.lang.NullPointerException
>     at Discount.main(Discount.java:15)

The exception message told you very specifically that a
NullPointerException occurred in line 15 of your code.

And this page explains what is a NullPointerException:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/NullPointerException.html

Read what a NullPointerException is, and then look at your code.
Patricia Shanahan - 09 Oct 2007 14:08 GMT
>> Hello again. This time i have another code that isn't working. It is
>> like a ticket program... It should ask the user "how old are you?",
[quoted text clipped - 14 lines]
>
> Read what a NullPointerException is, and then look at your code.

For a wider view of dealing with run time problems, I've written up an
approach to debug that works for me. See
http://home.earthlink.net/~patricia_shanahan/debug/

However, for this problem it all reduces to what kcwong said.

Patricia
Lew - 09 Oct 2007 14:19 GMT
>> Hello again. This time i have another code that isn't working. It is
>> like a ticket program... It should ask the user "how old are you?",
[quoted text clipped - 14 lines]
>
> Read what a NullPointerException is, and then look at your code.

Then figure out what gets returned that might be null.  We have to guess which
line is line 15, since you don't tell us.

BTW, please do not embed TABs in Usenet listings.  Use spaces to indent code
samples.

Also, bear in mind that while the books might use double to represent monetary
amounts, in the Real World you should /never/ do that.

Signature

Lew

the_transcriber@yahoo.com - 10 Oct 2007 06:06 GMT
> BTW, please do not embed TABs in Usenet listings.  Use spaces to indent code
> samples.
[quoted text clipped - 4 lines]
> --
> Lew

Thanks for your help. I don't understand what you mean by your last
sentence, thanks!
Lew - 10 Oct 2007 07:01 GMT
Lew said:
>> Also, bear in mind that while the books might use double to represent monetary
>> amounts, in the Real World you should /never/ do that.

> I don't understand what you mean by your last sentence, thanks!

The book you quoted had this:
> double price = 0.00;

That is a double, used to represent a monetary amount, right?

Don't do that.

Incidentally, '0.00' is a silly double literal.  '0.0' is more normal, or '0.'
or '0D'.

Signature

Lew

RedGrittyBrick - 10 Oct 2007 20:46 GMT
>> Also, bear in mind that while the books might use double to represent monetary
>> amounts, in the Real World you should /never/ do that.
>
> Thanks for your help. I don't understand what you mean by your last
> sentence, thanks!

http://www.javapractices.com/Topic213.cjp

http://catb.org/jargon/html/G/GIYF.html
AndrewTK - 09 Oct 2007 16:37 GMT
Just this once, because I can and because you are a newbie programmer.
Note that it is also a simple example of how to go about debugging
simple programs.

On Oct 9, 7:42 am, the_transcri...@yahoo.com wrote:
> java.lang.NullPointerException
>     at Discount.main(Discount.java:15)

As the others have pointed out, you have to tell us where line 15 in
your code is for us to help you - newlines etc and snipped code change
these kind of things when posting.

Given your code, the only line that would make sense to raise a
NullPointerException is effectively line 15 lines after the import
statement, the assumed 'line 1':
> reply = myScanner.findInLine(".").charAt(0);

It must be findInLine() return null, since:
-myScanner has not been re-assigned to since creation and the last use
did not raise NullPointerException, and hence cannot be null
-charAt() returns a char data type, which is not an Object, hence
cannot be null

Now you just have to figure out why myScanner.findInLine(".") is
returning null

The documentation here:

- http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#findInLine(java.l
ang.String
)
states that findInLine(pattern_string) is the same as
findInLine(Pattern.compile(pattern_string) )

- http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#findInLine(java.u
til.regex.Pattern
)
states that the method will return null if the pattern is not found.

>From your console dump:
> How old are you? 51
> Have a coupon? (Y/N) Exception in thread "main"
> java.lang.NullPointerException
>     at Discount.main(Discount.java:15)

It would seem the program saw no input. That would explain why it does
not find anything, hence null and your program breaking. Now find out
why it saw no input.

SO.....

Lessons to learn:
-NullPointerExceptino says you got null specifically, at the line the
exception dump is telling you. Look there first.
-Look at the documentation for the involved methods. If a variable
turns out to be null, look where it was last assigned to.
{ http://java.sun.com/j2se/1.5.0/docs/api/ } this page is your friend.
Use it.
-And what Lew said.

Good luck learning,

Andrew K
Lew - 09 Oct 2007 23:11 GMT
> { http://java.sun.com/j2se/1.5.0/docs/api/ } this page is your friend.
> Use it.

<http://java.sun.com/javase/6/docs/api/>
is an even better friend.

Signature

Lew

kcwong - 10 Oct 2007 04:17 GMT
> > {http://java.sun.com/j2se/1.5.0/docs/api/} this page is your friend.
> > Use it.
[quoted text clipped - 4 lines]
> --
> Lew

I got the URL from my browsing history when I replied. At first I
tried to edit the version from 1.5.0 to 1.6, but that returned a 404.
I made a few more guesses but all failed... then I gave up and just
post the 1.5 one.

Sun sure has a weird way of naming things... and they just can't
design a scheme and follow through with it.

If you have installed various versions of JDK and JRE on a Windows
machine, you'd notice the mess Sun created in your registry. And the
JDK folder names.

And since the weird naming involves the registry, I'm not convinced
this is because of those evil marketing guys. ;)
Lew - 10 Oct 2007 05:09 GMT
> And since the weird naming involves the registry  ...

Not on Linux systems, it doesn't.

Check out:
<http://java.sun.com/javase/namechange.html>

RTFM is a wonderful thing.

Signature

Lew

kcwong - 10 Oct 2007 06:53 GMT
> > And since the weird naming involves the registry  ...
>
[quoted text clipped - 7 lines]
> --
> Lew

Let's hope they will stick with their plan this time... or will we see
J3SE and a URL ilke (http://java.sun.com/j3se/1.7.0/docs/api/)
someday. ;)
Brian - 09 Oct 2007 16:52 GMT
>How old are you? 51
>Have a coupon? (Y/N) Exception in thread "main"
>java.lang.NullPointerException
>    at Discount.main(Discount.java:15)
>
>    public static void main(String args[]) {

should be:
public static void main(String[] args) {
>        System.out.print("Have a coupon? (Y/N) ");
>        reply = myScanner.findInLine(".").charAt(0);

change this to:
reply = myScanner.next().charAt(0);

then the program will run

/Brian
Christopher Benson-Manica - 09 Oct 2007 20:59 GMT
>>       public static void main(String args[]) {

> should be:
> public static void main(String[] args) {

Although that's a stylistic imperative rather than a functional one.
 
Signature

 C. Benson Manica    | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
  sdf.lonestar.org   | Google groups, due to rampant unchecked spam.

Lew - 09 Oct 2007 23:10 GMT
the_transcriber@yahoo.com wrote:
>>>       public static void main(String args[]) {

Brian <mail@del_oddball_ete.dk> wrote:
>> should be:
>> public static void main(String[] args) {

> Although that's a stylistic imperative rather than a functional one.

Is it really an "imperative" at all?

Logically it makes sense, at least to me, in that the type of 'args' is
"String array", and "String [] args" reflects that.  I read it as declaring a
"String array args".  One is tempted to read the other form as "String args
array", which is obtuse at best.

Nearly all references to array declarations in Java literature follow the
"Foo [] variable" pattern.  This suggests that programmer-to-programmer
communication is improved by the "Foo [] variable" pattern.

If one values clarity of expression and ease of communication, one would
validly conclude that indeed it is a stylistic imperative to follow the cited
advice.

Signature

Lew

Christopher Benson-Manica - 10 Oct 2007 21:37 GMT
> the_transcriber@yahoo.com wrote:
>>>>       public static void main(String args[]) {

> Brian <mail@del_oddball_ete.dk> wrote:
>>> should be:
>>> public static void main(String[] args) {

>> Although that's a stylistic imperative rather than a functional one.

> Is it really an "imperative" at all?

My semantic analyzer may be buggy - I can't tell whether this is a
serious or rhetorical question...

> If one values clarity of expression and ease of communication, one would
> validly conclude that indeed it is a stylistic imperative to follow the cited
> advice.

Am I correct in believing that you agree with the original advice and
that it is indeed a "stylistic imperative"?

Signature

 C. Benson Manica    | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
  sdf.lonestar.org   | Google groups, due to rampant unchecked spam.

Lew - 11 Oct 2007 07:41 GMT
>>> Although that's a stylistic imperative rather than a functional one.

> Am I correct in believing that you agree with the original advice and
> that it is indeed a "stylistic imperative"?

I agree that it's good advice.

Signature

Lew

the_transcriber@yahoo.com - 10 Oct 2007 08:03 GMT
> change this to:
> reply = myScanner.next().charAt(0);
>
> then the program will run
>
> /Brian

Thanks for your help. Is there an 'easy' way to explain what the
charAt(0)  part means?
AndrewTK - 10 Oct 2007 18:07 GMT
On Oct 10, 8:03 am, the_transcri...@yahoo.com wrote:
> Thanks for your help. Is there an 'easy' way to explain what the
> charAt(0)  part means?

It's to do with accessing characters in a text String ('string')

Consider this string:

 String s = "abcde"

The length of the string is 5 so:
 s.length()
returns 5

The 'a' is in the first position, the 'b' in second etc BUT
The counting starts at ZERO so, the charAt() method (which you can
interpret as 'get character at position') returns the charcater at the
position you specify:
 s.charAt(0)
returns 'a'

NOTE THE DIFFERENCE between 'a' and "a"
'a' --> a char data type; chars cannot be null; 'a' == 'a' is always
true; 'hi' is not a character. It is actually a syntax error.

"a" --> a String object; Strings can be null; comparison rules apply

For the following definition of strings:
 String str1 = "hi";
 String str2 = "hi";
--> [str1 == str2] will normally return false (due to JVM internals
and compiler design, this varies).
--> [str1.equals(str2)] will ALWAYS return true

As a general rule, ALWAYS use equals() to compare strings. You want to
know more about object referencing to stray from this rule, which you
probably will never need to.

Hope that helps.

Andrew K
Lew - 11 Oct 2007 07:43 GMT
> On Oct 10, 8:03 am, the_transcri...@yahoo.com wrote:
>> Thanks for your help. Is there an 'easy' way to explain what the
[quoted text clipped - 3 lines]
>
> Consider [several points of excellent advice]

The easiest way to explain what String.charAt(0) means is to say,
<http://java.sun.com/javase/6/docs/api/java/lang/String.html#charAt(int)>

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.