Results 1 to 9 of 9
  1. #1
    reddens84 is offline Member
    Join Date
    Jul 2014
    Posts
    12
    Rep Power
    0

    Question Help with validating input

    I'm trying to write a program that calculates the factorials of the numbers 1 through 10, based on user input... My problem is that I don't know how to address the possibility of the user entering something other than a number. When I test the following code by entering a letter, I get an Input Mismatch exception. I'd like to be able to inform the user that the entry is invalid, and ask for another response. Here is my program thus far:

    Java Code:
    import java.util.Scanner;
    
    public class Factorial
    {
        public static String entryString;
        public static char entryChar;
        public static Scanner input = new Scanner(System.in);
        
        public static void main(String[] args)
        {
            long response;
            long fact;
            final char YES_OPTION = 'y';
            int count = 0;
            
            do
            {System.out.print("Enter an integer in the range 1 to 10: ");
            
            response = input.nextLong();
            
            if((response > 10 || response < 1) && count < 2)
                {
                    System.out.println("Number entered must be between 1 and 10.");
                    count++;
                    recycle();
                }
            else if ((response > 10 || response < 1) && count == 2)
            {
                break;
            }
            else if (response > 0 || response < 11)
                {
                    fact = factorial(response);
                    System.out.print("The factorial of " + response + " equals ");
                    System.out.println(fact + "\n\n\n");
                    System.out.print(response + "! = ");
                            
                    for(long i = 1; i < response; i++ )
                    {
                        System.out.print(i + " * ");
                    }
                    System.out.print(response + " = ");
                    System.out.println(fact);
                    System.out.println();
                    
                    count = 0;
                    
                    recycle();
                }
    
            }
            
            while(Character.toLowerCase(entryChar) == YES_OPTION);
            
            System.out.println("Goodbye.");
    
        }
        
        public static long factorial (long input)
    {
      long x, fact = 1;
      for ( x = input; x > 1; x--)
         fact *= x;
    
      return fact;
    
    }
        public static void recycle()
        {
            input.nextLine();
            
            System.out.print("Continue? (Y/N): ");
            
            entryString = input.nextLine();
            
            entryChar = entryString.charAt(0);
        }
    }
    Any help would be greatly appreciated.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Help with validating input

    That's where catching Exceptions come in handy: if you enter a 'non-number', the nextLong() method throws an Exception. All you have to do is try { ... } catch (Exception e) { <not a number supplied> }.

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  3. #3
    reddens84 is offline Member
    Join Date
    Jul 2014
    Posts
    12
    Rep Power
    0

    Default Re: Help with validating input

    As the forum name implies, I'm very new to Java... I've tried to read up on try/catch blocks, but somehow I don't seem to be getting it.

    This is what I tried:

    Java Code:
     try
            {
                response = input.nextLong();
            }
            
            catch (Exception e)
                    {
                        System.out.println("Not a number.");
                        recycle();
                        System.out.print("Enter an integer in the range 1 to 10: ");
                        response = input.nextLong();
                    }
    It works, but only for the first iteration (i.e., after I enter one non-numeric value, it prints the error and lets me try again with new input... But if I enter another invalid value, it goes back to the input mismatch)... What can I do to get it to work every time (or at least three tries, as I have with numeric values outside of the 1-10 range)? Do I have to put another for loop/counter inside the catch, or is there another way? I mean, theoretically someone should only have to be told once that you have to enter a number, but... I'd like to be prepared.
    Last edited by reddens84; 09-13-2014 at 10:01 AM.

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Help with validating input

    That is just programming; assume a simple method that returns a number or it loops if no number were supplied; it could look like this:

    Java Code:
    private long getNumber(Scanner input) {
       while (true) {
          try {
             return input.nextLong();
          }
          catch (Exception e) {
             System.out.println("that was not a number.");
          }
       }
    }
    Your code should call that method when it wants a number.

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  5. #5
    reddens84 is offline Member
    Join Date
    Jul 2014
    Posts
    12
    Rep Power
    0

    Default Re: Help with validating input

    Thanks for the help.

    Just by the by, do you have any suggestions to make anything else in my code more efficient/readable? Maybe I'm wrong, but I just get the feeling that I'm going through some unnecessary steps.

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Help with validating input

    Quote Originally Posted by reddens84 View Post
    Thanks for the help.

    Just by the by, do you have any suggestions to make anything else in my code more efficient/readable? Maybe I'm wrong, but I just get the feeling that I'm going through some unnecessary steps.
    Yep, there's one small thingy that's disturbing; for 3! you're code is printing 1 * 2 * 3 * = 6 (note that trailing *); it can easily be corrected:

    Java Code:
    String op= "";
    for (int i= 1; i <= response; i++) {
       System.out.print(op+i); op= " * ";
    }
    But that's just me ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  7. #7
    reddens84 is offline Member
    Join Date
    Jul 2014
    Posts
    12
    Rep Power
    0

    Default Re: Help with validating input

    Hmm, that's odd... When I run it, that extra asterisk at the end isn't there.

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Help with validating input

    You must've changed the code; I'm referring to line #38 ... #42 in the code you posted.

    edit: you're right, I misread your code; sorry about that.

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  9. #9
    reddens84 is offline Member
    Join Date
    Jul 2014
    Posts
    12
    Rep Power
    0

    Default Re: Help with validating input

    No worries Initially I did have the code where it printed the trailing asterisk, but I fixed that after the first time I saw it.

Similar Threads

  1. validating int input
    By jazzo in forum New To Java
    Replies: 6
    Last Post: 05-05-2013, 04:03 AM
  2. Validating user input
    By dfarni in forum New To Java
    Replies: 1
    Last Post: 08-28-2011, 05:42 AM
  3. Help with validating input into an array
    By kcoltharp in forum New To Java
    Replies: 1
    Last Post: 02-25-2011, 10:05 AM
  4. SDF validating date input
    By getshum in forum New To Java
    Replies: 2
    Last Post: 02-03-2011, 09:37 AM
  5. Validating Jtable
    By anilkumar_vist in forum Advanced Java
    Replies: 1
    Last Post: 11-24-2009, 03:54 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •