Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Other possible issues with if statements - book return program

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Other possible issues with if statements - book return program

    I'm working a program that's meant to act as book return program; it'll ask you to enter a number, corresponding to the type of book you have, and depending on that number, will add 1 to a static number (for example, 34 books for Sci-Fi) and display the outcome in the console.
    When I run it, and try to press 2 for Non-Fiction, nothing will happen. When I press it again, then the "Thank you for returning this Non-Fiction... etc" message will display, but my desired message in the console won't come up (which should say "We now have 29 Non-Fiction Books.")

    You know what I mean? This is the error I get:

    Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Num berFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:504)
    at java.lang.Integer.parseInt(Integer.java:527)
    at BookReturns.main(BookReturns.java:23)

    And here's my code:

    import java.util.Scanner;
    import javax.swing.JOptionPane;
     
    public class BookReturns {
     public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     
     int scifi = 34;
     int nonfiction = 28;
     
     String scifibookString = JOptionPane.showInputDialog(null, "What type of book do you have?\nEnter 1 for Sci-Fi,\nEnter 2 for Non-Fiction,\nEnter 3 for Graphic Novel,\nEnter 4 for Novel: ");
      int scifibook = Integer.parseInt(scifibookString);
     
      if (scifibook == 1){
       scifi += 1;
     
    	JOptionPane.showMessageDialog(null, "Thank you for returning this Sci-Fi book. Have a nice day!", "Thank you!", JOptionPane.INFORMATION_MESSAGE);
    	System.out.println("We now have " + scifi + " Sci-Fi books.");
    	System.exit(0);
    	}
     
     String nonfictionbookString = JOptionPane.showInputDialog(null, "What type of book do you have?\nEnter 1 for Sci-Fi,\nEnter 2 for Non-Fiction,\nEnter 3 for Graphic Novel,\nEnter 4 for Novel: ");
      int nonfictionbook = Integer.parseInt(nonfictionbookString);
     
      if (nonfictionbook == 2){
       nonfiction += 1;
     
    	JOptionPane.showMessageDialog(null, "Thank you for returning this Non-Fiction book. Have a nice day!", "Thank you!", JOptionPane.INFORMATION_MESSAGE);
    	System.out.println("We now have " + nonfiction + " Non-Fiction books.");
    	System.exit(0);
    	}
     
     
    	}
    }


  2. #2
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Other possible issues with if statements - book return program

    That's the kind of error message you get if you click "OK" without entering anything in the dialog box.
    Check the return value of the String before you try parseInt.

    Note that if you click "Cancel" it returns a null value, so you should check for null before anything else.
    Then check the length of the String to make sure it's not zero.

    Note, also that if you enter something other than an integer, you will get a NumberFormatException. Eventually you will want to catch that to keep the program from crashing. But for now, maybe just check for null and zero-length Strings.


    Cheers!

    Z
    Last edited by Zaphod_b; October 31st, 2012 at 08:04 PM.

  3. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Other possible issues with if statements - book return program

    I kind of don't understand what you mean. I apologize, I'm a complete newbie at this.

    When I enter 1 for Sci-Fi, it works as intended. When I enter 2 for Non-Fiction, that's when nothing happens the first time. But if I enter 2 again, then it'll work.

    The return value of the String would be what the user inputs, right? Or am I understanding that wrong?
    And what do you mean by checking the String to make sure it isn't zero?

  4. #4
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Other possible issues with if statements - book return program

    Quote Originally Posted by Shenaniganizer View Post
    I kind of don't understand what you mean. ...
    The problem with gui programs is that I can't look over your shoulder and see exactly what you are doing.

    Try the following. Hit 'Cancel'
    Try again and click "OK" without entering anything.
    Then try again and go through the steps that resulted in your puzzlement (Enter 2 for the first one and see where it goes from there.)


    //
    // BookReturns2.java from Zaphod_b
    //
    // Save your original code for comparison.
    //
    import java.util.Scanner;
    import javax.swing.JOptionPane;
     
    public class BookReturns2 {
        public static void main(String [] args) {
        Scanner input = new Scanner(System.in);
     
        int scifi = 34;
        int nonfiction = 28;
     
        int scifibook = 0;
        int nonfictionbook = 0;
     
        String scifibookString = JOptionPane.showInputDialog(null,
                "What type of book do you have?\n" +
                "Enter 1 for Sci-Fi,\n" +
                "Enter 2 for Non-Fiction,\n" +
                "Enter 3 for Graphic Novel,\n" +
                "Enter 4 for Novel: ");
     
     
        // For debugging show what was returned
        System.out.println("scifibookString = <" + scifibookString + ">");
     
        // For program testing
        if (scifibookString == null) {
            // Do whatever you need to do if the user hit 'Cancel'
            // For now, just print something on System.out
            System.out.println("You cancelled the first book transaction");
        }
        else if (scifibookString.length() == 0) {
            // Do whatever you need to do if the user hit 'OK'
            // without entering anything.
            // For now, just print something on System.out
            System.out.println("You didn't enter anything.");
        }
        else {
            // For a "real" program probably put everything in
            // a try{}catch(){} block to keep invalid entries
            // from crashing the program.
            // For now, just let the chips fall where they may.
            scifibook = Integer.parseInt(scifibookString);
        }
     
        if (scifibook == 1){
            scifi += 1;
     
            JOptionPane.showMessageDialog(null,
                    "Thank you for returning this Sci-Fi book. Have a nice day!",
                    "Thank you!",
                    JOptionPane.INFORMATION_MESSAGE);
            System.out.println("We now have " + scifi + " Sci-Fi books.");
            System.out.println("Exit point number 1");
            System.exit(0);
        }
     
        String nonfictionbookString = JOptionPane.showInputDialog(null,
                "What type of book do you have?\n" +
                "Enter 1 for Sci-Fi,\n" +
                "Enter 2 for Non-Fiction,\n" +
                "Enter 3 for Graphic Novel,\n" +
                "Enter 4 for Novel: ");
     
        // Go through all of the above stuff checking for null or empty
        // string returned from the message dialog box
     
        // For debugging show what was returned
        System.out.println("nonfictionbookString = <" + nonfictionbookString + ">");
     
        if (nonfictionbookString == null) {
            // Do whatever you need to do if the user hit 'Cancel'
            // For now, just print something on System.out
            System.out.println("You cancelled the second book transaction");
        }
        else if (nonfictionbookString.length() == 0) {
            // Do whatever you need to do if the user hit 'OK'
            // without entering anything.
            // For now, just print something on System.out
            System.out.println("You didn't enter anything in the second dialog box.");
        }
        else {
            // For a "real" program probably put everything in
            // a try{}catch(){} block to keep invalid entries
            // from crashing the program.
            // For now, just let the chips fall where they may.
            nonfictionbook = Integer.parseInt(nonfictionbookString);
        }
     
        if (nonfictionbook == 2){
            nonfiction += 1;
            JOptionPane.showMessageDialog(null,
                "Thank you for returning this Non-Fiction book. Have a nice day!",
                "Thank you!",
                JOptionPane.INFORMATION_MESSAGE);
            System.out.println("We now have " + nonfiction + " Non-Fiction books.");
            System.out.println("Exit point number 2");
            System.exit(0);
        }
     
     
        }
    }

    Maybe you can see what I was talking about: If you click "OK" without entering anything it returns with a String whose length is zero. the Integer.parseInt() method in your original code chokes on that, and you get the error message that you reported.

    If you click "Cancel" it returns with a null value instead of a reference to something useful. The Integer.parseInt() method in your original code chokes on that, and you get a NullPointerException error.

    Go back to your original code (without my if(){}else(){} stuff protecting against a couple of kinds of exceptions). Follow the same sequence of inputs and see what happens with the error messages.



    Cheers!

    Z
    Last edited by Zaphod_b; October 31st, 2012 at 08:41 PM.

Similar Threads

  1. Issues with my ordering program - if statement issues?
    By Shenaniganizer in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 31st, 2012, 11:17 PM
  2. Address Book program in Java
    By DaveNAchill in forum Paid Java Projects
    Replies: 3
    Last Post: January 6th, 2012, 04:03 AM
  3. Address Book Program in java
    By DaveNAchill in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 11th, 2011, 09:25 AM
  4. Address Book Program Issues
    By Gamb1t in forum What's Wrong With My Code?
    Replies: 208
    Last Post: August 25th, 2011, 09:43 PM
  5. [SOLVED] Fixing of bug in number guessing game
    By big_c in forum Loops & Control Statements
    Replies: 6
    Last Post: April 16th, 2009, 03:15 AM