Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Validate user input

    Hello... I'm new to Java and I have written a few pieces of code but for the life of me, i haven't grasp the concept of validating user input. It seems to be kicking my rear end. I seen many pages, but cant seem to grasp the premise. Looking any help and information.

    Here's my code... im looking to validate the user input to determine if the number entered by user is a binary number or not. If the number entered is numbers and letters then its suppose to display "Try again." Until the user enters a correct binary number.

    The whole program is part of a loop at the end to repeat the process if the user chooses to.


    Java Code:
    import java.util.Scanner;
    
    
    public class NewestOne
    {
       public static void main(String[] args)
       {
    
    
         Scanner keyboard = new Scanner( System.in );
    
    
        // Variables and Inputs
        char repeat;
        String in;
    
       do
        {
    
               System.out.print("Enter a binary string ");
            System.out.println();
            String binary = keyboard.nextLine();
            System.out.println();
            System.out.println("You entered " + binary);
            System.out.println("its base 10 equivalent is "+ Integer.parseInt(binary,2));
    
    
               System.out.println("Continue? y/n... or any other character to quit");
               in = keyboard.nextLine();
               repeat = in.charAt(0);
               System.out.println();
    
    
         }
         while (repeat == 'Y' || repeat == 'y');
    
    
        }
    
    
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Validate user input

    determine if the number entered by user is a binary number or not.
    Is that number a String consisting of the either "1" or "0" characters?
    I don't see that the code tests the input String for that.
    Whoops missed the base/radix 2 in parseInt()
    Last edited by Norm; 10-18-2016 at 01:09 PM.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    Yes, the string tests the input any binary number entered.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Validate user input

    Quote Originally Posted by westcoastrendkill View Post
    Yes, the string tests the input any binary number entered.
    The string does not test anything. Your code presumes that the input string represents a binary number.
    Your Integer.parseInt() method call will throw a number format exception if the string is not 1's and 0's
    (based on the specified radix). I recommend you investigate try/catch blocks and use that to validate
    the user input.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    My professor says we can't use try and block cause we haven't learned it in our class yet. Funny thing, is that i found a method to use it and it works but like he said we can't use it.

    Any other examples or suggestions would be great.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Validate user input

    Okay, the how about simply scanning the String for 1's and 0's? Check out the String.charAt() method.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    Never seen that before. Anyway you could give me an example. thanks

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Validate user input

    If I did that there wouldn't be much left for you to do. Just read the API for the method. It takes an integer argument to get the character
    at the designated position in the string. That character must either be a 1 or a 0. Do some experimenting with the method.

    BTW, it is absolutely essential to have a link to the Java API. If you don't have one, here it is. Make certain you bookmark it.

    Overview (Java Platform SE 8 )

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    Awesome thanks for the info. I feel really bad asking for any help but when my professor is completely useless and there isnt another to help im kind of at my wits end.

  10. #10
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    Hey man... could you go over my code that wrote last night and today.. I know i can't use it but i still want to know what's up with it. If you run the program and input non binary numbers it works fine and even when run binary numbers. The problem is when you click yes to start the program again and input a non binary number it says try that again but it shows the continue y/n at the bottom.

    Validate user input-error.png

    Java Code:
    import java.util.Scanner;
    
    public class Main
    {
       public static void main(String[] args)
       {
    
     	Scanner keyboard = new Scanner( System.in );
    
    	// Variables and Inputs
    
    	int x = 1;
    	char repeat;
    	String binary;
    	String in;
    
       do{
       		do{
       			try{
    
           		System.out.print("Enter a binary string ");
    			System.out.println();
    			binary = keyboard.nextLine();
    			System.out.println();
    			System.out.println("It's base 10 equivalent is "+ Integer.parseInt(binary,2));
    			x=2;
    		}
    			catch(Exception e){
    			System.out.println("Sorry. Try Again");
    			System.out.println();
    
    		}
    		}while (x==1);
    
    
       			System.out.println("Wanna do it again, type 'y' or type 'n' to quit.");
    	   		in = keyboard.nextLine();
    	   		repeat = in.charAt(0);
    			System.out.println();
    
    		 }
    		 while (repeat == 'Y' || repeat == 'y');
    
    
    
    
        }
    
    }

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Validate user input

    After you prompt for y or n you need to set x = 1 again so that it stays in the inner loop.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Validate user input

    Note: using a variable named x with values 1 or 2 or ?? makes the code harder to understand. What is the purpose of using x? If it is to control the looping and will have 2 values, then it should be a boolean variable with a name with meaning like continueWhileBad that starts at true and is set false when a valid number is found.
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    Quote Originally Posted by Norm View Post
    Note: using a variable named x with values 1 or 2 or ?? makes the code harder to understand. What is the purpose of using x? If it is to control the looping and will have 2 values, then it should be a boolean variable with a name with meaning like continueWhileBad that starts at true and is set false when a valid number is found.
    Alright i took your advice and changed the x variables to boolean variables with a true and false setting and keep getting the same problem as i mentioned above.
    Here's the code

    Java Code:
    import java.util.Scanner;
    
    public class Main
    {
       public static void main(String[] args)
       {
    
     	Scanner keyboard = new Scanner( System.in );
    
    	// Variables and Inputs
    
    	char repeat;
    	String binary;
    	String in;
    	boolean WhileBad = true;
    
       do{
       		do{
       			try{
    
           		System.out.print("Enter a binary string ");
    			System.out.println();
    			binary = keyboard.nextLine();
    			System.out.println();
    			System.out.println("It's base 10 equivalent is "+ Integer.parseInt(binary,2));
    			WhileBad = false;
    		}
    			catch(Exception e){
    			System.out.println("Sorry. Try Again");
    			System.out.println();
    
    		}
    		}while (WhileBad == true);
    
    
       			System.out.println("Wanna do it again, type 'y' or type 'n' to quit.");
    	   		in = keyboard.nextLine();
    	   		repeat = in.charAt(0);
    			System.out.println();
    
    		 }
    		 while (repeat == 'Y' || repeat == 'y');
    
    
    
    
        }
    
    }

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Validate user input

    Java Code:
    public class Main
    {
        public static void main(String[] args)
        {
    
            Scanner keyboard = new Scanner( System.in );
    
            char repeat;
            String binary;
            String in;
            boolean WhileBad = true;
    
            do {
                do {
                    try {
    
                        System.out.print("Enter a binary string ");
                        System.out.println();
                        binary = keyboard.nextLine();
                        System.out.println();
                        System.out.println("It's base 10 equivalent is "+ Integer.parseInt(binary,2));
                        WhileBad = false;
                    } catch(Exception e) {
                        System.out.println("Sorry. Try Again");
                        System.out.println();
    
                    }
                } while (WhileBad == true);
                
                System.out.println("Wanna do it again, type 'y' or type 'n' to quit.");
                in = keyboard.nextLine();
                repeat = in.charAt(0);
                System.out.println();
    
            } while (repeat == 'Y' || repeat == 'y');
        }
    }
    Tidied up the code so I can read it a little easier.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Validate user input

    Java Code:
                    } catch(Exception e) {
                        System.out.println("Sorry. Try Again");
                        System.out.println();
    
                    }
    The problem is in here.
    As jim says, if you have an exception after successfully entering a valid number then WhileBad (see below for naming suggestions) will be false and is never set to true again.
    There are two options to this.
    Either set WhileBad to false in here, or narrow the scope of the variable. You only need WhileBad inside the first loop, so declare it there and not outside that loop.
    Java Code:
    do {
        boolean WhileBad = true;
        do {
        } while WhileBad
    } while repeat;
    That also highlights the naming issue.
    'while WhileBad' sounds wrong...it should be something like 'while invalidInput' (and note the camel case).
    Also note that <boolean variable> == true is not good practice. It's already a boolean, so no need for the comparison.
    Last edited by Tolls; 10-20-2016 at 09:29 AM. Reason: Oops on the boolean values
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  16. #16
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    So i took out the while loop at the end and now im getting the error i had before on the first try rather than the second.

    Java Code:
    import java.util.Scanner;
    public class Main
    {
        public static void main(String[] args)
        {
    
            Scanner keyboard = new Scanner( System.in );
    
            char repeat;
            String binary;
            String in;
    		boolean invalidInput;
    
            	do {
    
                	try {
    
                        System.out.print("Enter a binary string ");
                        System.out.println();
                        binary = keyboard.nextLine();
                        System.out.println();
                        System.out.println("It's base 10 equivalent is "+ Integer.parseInt(binary,2));
    					invalidInput = true;
    
                    } catch(Exception e) {
                        System.out.println("Sorry. Try Again");
                        System.out.println();
    					invalidInput = false;
                    }
    
                System.out.println("Wanna do it again, type 'y' or type 'n' to quit.");
                in = keyboard.nextLine();
                repeat = in.charAt(0);
                System.out.println();
    
            } while (repeat == 'Y' || repeat == 'y');
        }
    }

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Validate user input

    Why did you remove the inner loop?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  18. #18
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    Sorry i messed up. I was a bit out of it last night. I ended up putting the false under the catch (exception e). Only left it there. Problem not sure what to put in the while loop now.. I got all confused and everything.

    Java Code:
     try {
    
    			                    System.out.print("Enter a binary string ");
    			                    System.out.println();
    			                    binary = keyboard.nextLine();
    			                    System.out.println();
    			                    System.out.println("It's base 10 equivalent is "+ Integer.parseInt(binary,2));
    
    
    			                } catch(Exception e) {
    			                    System.out.println("Sorry. Try Again");
    			                    System.out.println();
    			                    invalidInput=false;
    
    			                }
    			            } while (not sure what to put here);
    
    			            System.out.println("Wanna do it again, type 'y' or type 'n' to quit.");
    			            in = keyboard.nextLine();
    			            repeat = in.charAt(0);
    			            System.out.println();
    
    			        } while (repeat == 'Y' || repeat == 'y');
    			    }
    }

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Validate user input

    Sorry i messed up.
    Yes. The posted code in #18 is missing the start of both the loops.
    And there is no catch for the try
    If you don't understand my response, don't ignore it, ask a question.

  20. #20
    Join Date
    Oct 2016
    Posts
    27
    Rep Power
    0

    Default Re: Validate user input

    Java Code:
    import java.util.Scanner;
    public class Main
    {
        public static void main(String[] args)
        {
    
            Scanner keyboard = new Scanner( System.in );
    
            char repeat;
            String binary;
            String in;
    		boolean invalidInput;
    
    
    
    			        do {
    			            do {
    			                try {
    
    			                    System.out.print("Enter a binary string ");
    			                    System.out.println();
    			                    binary = keyboard.nextLine();
    			                    System.out.println();
    			                    System.out.println("It's base 10 equivalent is "+ Integer.parseInt(binary,2));
    
    
    			                } catch(Exception e) {
    			                    System.out.println("Sorry. Try Again");
    			                    System.out.println();
    			                    invalidInput=false;
    
    			                }
    			            } while (not sure what to put here);
    
    			            System.out.println("Wanna do it again, type 'y' or type 'n' to quit.");
    			            in = keyboard.nextLine();
    			            repeat = in.charAt(0);
    			            System.out.println();
    
    			        } while (repeat == 'Y' || repeat == 'y');
    			    }
    }

Page 1 of 2 12 LastLast

Similar Threads

  1. Validate user input (positive and numerical)
    By neveser in forum New To Java
    Replies: 1
    Last Post: 11-28-2012, 10:00 AM
  2. How validate input against abstract class?
    By FadedAura in forum New To Java
    Replies: 1
    Last Post: 12-03-2011, 04:53 PM
  3. Replies: 2
    Last Post: 05-24-2011, 10:15 AM
  4. Replies: 2
    Last Post: 05-18-2010, 03:12 PM
  5. How do I validate user input from forms with Java?
    By rickywh in forum New To Java
    Replies: 2
    Last Post: 01-30-2010, 06:49 AM

Posting Permissions

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