Hi, I'm having a problem with reading from the char , coupon, and it comes up with an error saying

Exception in thread "main" java.lang.NullPointerException
        at input.Main.main(Main.java:27)

At the line which I read from the char, which is that myScan.findInLine bit, I am working from a beginning java programming book, and I'm pretty sure everything is the same but I still receive that error when I get up to that bit in the program(after it asks Do you have a coupon?)

public class Main {

    public static void main(String[] args) {
        int age = 0;
        char coupon;
        double price = 0;
       Scanner myScan = new Scanner(System.in);
      System.out.println("How old are you?");
      age = myScan.nextInt();
       System.out.println("Do you have a coupon?(Y/N)");
       coupon = myScan.findInLine(".").charAt(0);
       System.out.println(coupon);


       if (age >= 18 && age<=55 )
       {
               price = 11.25;
        }
        else
        {
           price = 9.25;
        }


        if(coupon=='y'||coupon=='Y') {
             price = price - 2.00;
         }
         else {
           System.out.println("No Coupon. Price Remains the same.");
         }

       System.out.println("The price will be:" + price);

Dani AI

Generated

The NullPointerException comes from calling charAt(0) on a null return from findInLine. After nextInt() the trailing newline is left in the Scanner buffer, and findInLine only searches the remainder of the current line. If that remainder is empty there is no match (so findInLine returns null) and charAt(0) triggers the NPE. That is why 's quick hack of swapping the prompts appears to "fix" the program — it avoids calling findInLine after a nextInt() and so the method actually finds a character.

Safer fixes (pick one):

  • Consume the newline after reading the int, then read the coupon line:

    int age = in.nextInt();
    in.nextLine();               // consume end-of-line left by nextInt()
    System.out.print("Coupon? ");
    String line = in.nextLine().trim();
    char coupon = line.isEmpty() ? 'N' : line.charAt(0);
  • Or read a token (skips whitespace/newlines) instead of using findInLine:

    char coupon = in.next().trim().charAt(0);

Also add simple validation: check the string is non-empty before calling charAt, and normalize case with Character.toUpperCase(coupon) when testing for 'Y'. Wrap nextInt() in a try/catch for InputMismatchException to handle bad age input.

In short: the NPE is caused by findInLine returning null because of the leftover newline from nextInt(). Either consume that newline with nextLine(), use next() to get the next token, or validate the findInLine result before using it.

Recommended Answers

All 2 Replies

Well
If you replace the place of this piece of code:

System.out.println("Do you have a coupon?(Y/N)");
            coupon = myScan.findInLine(".").charAt(0);
            System.out.println(coupon);

in the place of this piece of code :

System.out.println("How old are you?");
            age = myScan.nextInt();

to let your program be like this :

public static void main(String[] args) {
            int age = 0;
            char coupon;
            double price = 0;
            Scanner myScan = new Scanner(System.in);

            System.out.println("Do you have a coupon?(Y/N)");
            coupon = myScan.findInLine(".").charAt(0);
            System.out.println(coupon);

            System.out.println("How old are you?");
            age = myScan.nextInt();



            if (age >= 18 && age <= 55) {
                price = 11.25;
            } else {
                price = 9.25;
            }


            if (coupon == 'y' || coupon == 'Y') {
                price = price - 2.00;
            } else {
                System.out.println("No Coupon. Price Remains the same.");
            }

            System.out.println("The price will be:" + price);
        }

It will work !!
don't ask me why ... because I found it by trial and error !!
Some one tell us why??

Woah yea iit does work! But anyways, why?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.