Trouble with a code
I'm trying to write a program that asks how old you are, asks if you have a coupon, and will display the price of admisison. Here it is:
import java.util.Scanner;
class TicketPriceWithDiscount {
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("Do you 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(". Enjoy the show!");
}
}
It compiles fine, but when I run it, it says this:
How old are you? I say my age, works fine.
Do you have a coupon? (Y/N) Exception in thread "main" java.lang.NullPointerException at TicketPriceWithDiscount.main(TicketPriceWithDiscount.java:14)
It says that before I can even say yes or no. Please help me, I am confused to why it says this. Thank you!
> Sorry about that. I think it's failing on this line:
Well, there's no think about it. It tells you exactly what line number. Any decent editor will show line numbers.
> "reply = myScanner.findInLine(".").charAt(0);"
Either myScanner is null, or findInLine is returning null. Since you just used myScanner right before this, that can't be what's null, so findInLine must be returning null.
jverda at 2007-7-12 18:05:51 >

Hi,
The code compiles and runs on my machine, regardless if I choose 'Y' or 'N'. Though, is it possible you are running into problems with this line of code:
reply = myScanner.findInLine(".").charAt(0);
I can see what you are trying to do, that is, get a char value even though nextChar() is not a method of the Scanner class. I think your best bet is to just use next() to return the full input by the user which would allow you to easily test for "y", "n", "Y", "N", "yes", "no", "Yes", etc etc. Like so:
import java.util.Scanner;
class TicketPriceWithDiscount {
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
int age;
double price = 0.00;
String reply;
System.out.print("How old are you? ");
age = myScanner.nextInt();
System.out.print("Do you have a coupon? (Y/N) ");
reply = myScanner.next();
if (age >= 12 && age < 65) {
price = 9.25;
}
if (age < 12 || age >= 65) {
price = 5.25;
}
if ( (reply.equalsIgnoreCase("y")) || (reply.equalsIgnoreCase("yes")) )
{
price -=2.00;
}
else if (! ((reply.equalsIgnoreCase("n")) || (reply.equalsIgnoreCase("no"))) ){
System.out.println("Huh?");
}
System.out.print("Please pay $");
System.out.print(price);
System.out.print(". Enjoy the show!");
}
}