Results 1 to 3 of 3
Thread: Help with Null Pointer Exception
- 04-17-2010, 07:52 AM #1
Help with Null Pointer Exception
Hi guys, this is my 1st post here, but expect me to be active in the following days since I am currently learning how to program Java, and I have been given a book about it, and there is this particular code on the book which I am sure that I have copied exactly, up to every letter, but the problem is it is still showing an error when I scan for a character. Please help, thanks in advance!
Java Code:Scanner myScanner = new Scanner(in); int age; double price = 0.0; char reply; out.println("How old are you?"); age = myScanner.nextInt(); out.println("Do you have a coupon? Y/N"); reply = myScanner.findInLine(".").charAt(0); if (age >= 12 && age < 65) { price = 9.25; } else if (age < 12 || age >= 65) { price = 5.25; } if (reply == 'y' || reply == 'Y') { price -= 2.00; } else { out.println("Huh?"); } out.println("Please pay $" + price + ".");
-
You're running into one of the trickiest problems with using a java.util.Scanner object: capturing the end-of-line token.
When you do this:
your Scanner object grabs the next int token but not the next end-of-line token. So then when you do this:Java Code:System.out.println("How old are you?"); age = myScanner.nextInt();
The Scanner object grabs the end-of-line token and tries to process it but findInLine() will return null (see the API on this).Java Code:System.out.println("Do you have a coupon? Y/N"); reply = myScanner.findInLine(".").charAt(0);
The solution is to explicitly grab the end-of-line token after grabbing the int:
Java Code:[import java.util.Scanner; public class Fu3 { public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); int age; double price = 0.0; char reply; System.out.println("How old are you?"); age = myScanner.nextInt(); myScanner.nextLine(); // ***** add this! **** System.out.println("Do you have a coupon? Y/N"); reply = myScanner.findInLine(".").charAt(0); if (age >= 12 && age < 65) { price = 9.25; } else if (age < 12 || age >= 65) { price = 5.25; } if (reply == 'y' || reply == 'Y') { price -= 2.00; } else { System.out.println("Huh?"); } System.out.println("Please pay $" + price + "."); } }
- 04-17-2010, 04:41 PM #3
Similar Threads
-
Null pointer Exception
By peiceonly in forum New To JavaReplies: 8Last Post: 09-05-2010, 06:48 PM -
Null pointer exception
By talha06 in forum JDBCReplies: 5Last Post: 07-14-2009, 01:12 AM -
Help with null pointer exception
By gammaman in forum New To JavaReplies: 4Last Post: 07-14-2009, 12:23 AM -
Null Pointer Exception
By andre1011 in forum Advanced JavaReplies: 4Last Post: 02-07-2009, 03:30 AM -
getting a null pointer exception
By Rjava in forum XMLReplies: 4Last Post: 07-16-2008, 05:56 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks