Skip to main content

java.lang.NullPointerException line 13

1 reply [Last post]
metalcross911
Offline
Joined: 2010-12-21
Points: 0

why do i get an error like this after i input a number (in this case the number is 3)
___________________________________________________
(Copy from NetBeans output window)
run:
How old are you? 3
Exception in thread "main" java.lang.NullPointerException
at TicketPriceWithDiscount.main(TicketDiscount.java:13)
Have a coupon? (Y/N) Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
___________________________________________________
01 import java.util.Scanner;
02
03 class TicketPriceWithDiscount {
04
05 public static void main(String args[]) {
06 Scanner myScanner = new Scanner(System.in);
07 int age;
08 double price = 0.00;
09 char reply;
10 System.out.print("How old are you? ");
11 age = myScanner.nextInt();
12 System.out.print("Have a coupon? (Y/N) ");
13 reply = myScanner.findInLine(".").charAt(0); // What is wrong with this line?
14 if (age >= 12 && age < 65) {
15 price = 9.25;
16 }
17 if (age < 12 || age >= 65) {
18 price = 5.25;
19 }
20 if (reply == 'Y' || reply == 'y') {
21 price -= 2.00;
22 }
23 if (reply != 'Y' && reply != 'y'
24 && reply != 'N' && reply != 'n') {
25 System.out.println("Huh?");
26 }
27 System.out.print("Please pay $");
28 System.out.print(price);
29 System.out.print(". ");
30 System.out.println("Enjoy the show!");
31 }
32 }
when i swith the positions of lines 10, 11, 12 and 13 like this:
10 System.out.print("Have a coupon? (Y/N) ");
11 reply = myScanner.findInLine(".").charAt(0);
12 System.out.print("How old are you? ");
13 age = myScanner.nextInt();
It doesn't have the error. Why do i get the error?Does it have something to do with the jave version? i have jdk1.6.0_23

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
itanvi
Offline
Joined: 2011-04-20
Points: 0

Hi, Try this code, It may help. (Instead of changing the positions of the statements, I've used next() method of Scanner class)
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.next().charAt(0); // What is wrong with this line?
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!");