9 Replies - 6043 Views - Last Post: 15 February 2010 - 08:12 AM Rate Topic: -----

#1 RPDK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 11-February 10

Input Validation

Posted 14 February 2010 - 08:53 AM

import javax.swing.*;
               
public class TestName
{
	public static void main(String[] args) 
	{
                
   		boolean loop1 = false; 
  		boolean flag1 = false;
   		boolean flag2 = false;
   		String err1 = "Error - Do not enter numbers or spaces.";
   		String err2 = "Error - Do not enter letters or spaces.";
  		String name = null;
  		String name1 = null;
  		String age = null;
  		int a = 0;



		//Name - loop and validation

        
		while (!loop1) 
		{

		//do{}while loop to check if user hits cancel or X
			do 
			{ 

				name = JOptionPane.showInputDialog(null, "Enter name ", "NAME INPUT", JOptionPane.INFORMATION_MESSAGE); 
				if (name == null ) 
				{  
   					System.exit(0);
   					flag1 = false; 
				} 
				else 
				{ 
   					flag1 = true; 
				} 
			
			}while(!flag1);
			

			//checking if name contains digits                                              
			for (int i = 0; i < name.length(); i++) 
			{

				//I wanted to also include Character.isSpaceChar
				//but then it crashes all the time...
				if (Character.isDigit(name.charAt(i)))
				{
 				  flag2 = true;
				} 
				else 
				{
  				 flag2  = false;
				}
			}
			

	//check the name length, it should be greater than 13 or less than 2                                                            
		if (name.length() < 2 || name.length() > 13 )
		{
    		JOptionPane.showMessageDialog(null, " You can enter 2-13 characters", "ERROR", JOptionPane.ERROR_MESSAGE);
    		loop1 = false;
		}
		
		//flag2 == true stands for "contains digits or spaces"
		else if (flag2 == true)
		{
    		JOptionPane.showMessageDialog(null, err1, "ERROR", JOptionPane.ERROR_MESSAGE);                                              
    		loop1 = false;      
		}
		
		//if everything is correct the program will execute the following code
		else if (flag2 == false)
		{
			
    	   // converts the first letter to upper case
   			char one = name.toUpperCase().charAt(0);
    		String rest = name.substring(1);
            name1 = one+rest;
    		loop1 = true;       
		}
	}
              
	                          
//initializing loop variables                                   
loop1 = false;
flag1 = false;
flag2 = false;
                                        
                                        
                                        
        
//Age loop and validation                               
                                        
	while (!loop1)
	{

		//do {}while loop again to handle the cancel and X buttons
		do 
		{ 

			age = JOptionPane.showInputDialog(null, "Enter age ", "AGE INPUT", JOptionPane.INFORMATION_MESSAGE); 
			if (age == null || age.length() < 1) 
		    { 
   				System.exit(0);
   				flag1 = false; 
			} 
			else 
			{ 
   				flag1 = true; 
			} 
		} while(!flag1);
                                                
		//checking if name contains letters                                             
		for (int i = 0; i < age.length(); i++)
		{
        
			//here too, I wanted to include the Character.isSpacechar
			//but those crashes won't let me                
			if (Character.isLetter(age.charAt(i)))
			{
   				flag2 = true;
			}
			else 
			{
   				flag2  = false;
			}
		}
                                                
		//flag2 == true here  stands for "contains letters or spaces"                                           
		if (flag2 == true)
		{
   			JOptionPane.showMessageDialog(null, err2, "ERROR", JOptionPane.ERROR_MESSAGE);
  			loop1 = false;
		}
		else if ( flag2 == false)
		{
   
   			//converting the string to int in order to apply
   			// the age limit 13-80
   			a = Integer.parseInt(age);
   			if ( a < 13 || a > 80 )
   		    {
      			JOptionPane.showMessageDialog(null, "You can enter 13 - 80" , "ERROR", JOptionPane.ERROR_MESSAGE);
      			loop1 = false;
        	}
      		else
   			{
        		loop1 = true;                                                              
   			}
   		}
	}

	//prints name and age                                   
	JOptionPane.showMessageDialog(null,name1+" - "+a, "ERROR", JOptionPane.INFORMATION_MESSAGE);
}
}



The above code has given me many headaches so I'm resorting to you guys for some help.
The program contains two inputs, name and age, and I'd like to validate the name and age given
before using them later on.

I want the name to be one word, 2 - 13 characters and have the first letter capital.
With the above code I managed to convert the first letter to capital and prevent the user from entering digits.

However it does not work correctly. If the user enters a few characters first and then some digits an error message is shown
but if he types some digits first and then some letters the name is read as 'correct'!

Also the same happens with age. If the user types some digits first and then some letters an error message is shown, but if he
types some letters first the program crashes.

Also I'd like in the name field the program to check the vowels and consonants. If every 4 consonants there's no vowel
the program should pop up an error, preventing the user from entering names such as 'Fdgdffs'.

Edit: Indentation

This post has been edited by RPDK: 14 February 2010 - 09:54 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Input Validation

#2 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1011
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Input Validation

Posted 14 February 2010 - 09:13 AM

Please indent your code.. it is very hard to read..
try this as name validation.
just change the Scanner Object to a JOptionpane:
public class TestClass{

	public static void main(String[] args) {
		
		String name = "";
		int age = -1;
		Scanner input = new Scanner(System.in);
	
		boolean goodInput = false;
		
		//Name Validation:
		do{
			System.out.println("Enter Your Name");
			name = input.nextLine();
			
			if(name.isEmpty()){
				System.out.println("Name must Not be Empty");
			}
			else if(name.indexOf(" ") >= 0){
				System.out.println("No Spaces allowed");
			}
			else if(!Character.isUpperCase(name.charAt(0))){
				System.out.println("First char should be UpperCase");
			}
			else if(containsDigits(name)){
				System.out.println("Name Must Not Contain Digits");
			}
			else if(name.length() < 2 || name.length() > 13){
				System.out.println("name Must Contain 2 - 13 Characters");
			}		
			else{
				System.out.println("Name inputted");
				goodInput = true;
			}
		}while(!goodInput);
		
	}
	private static boolean containsDigits(String st){
		for(int i = 0 ; i < st.length(); i++){
			if(Character.isDigit(st.charAt(i))){
				return true;
			}
		}
		return false;
	}
}



this code will only validate name.
you can take the idea and implement on the age

**EDITED Typo

This post has been edited by japanir: 14 February 2010 - 09:18 AM

Was This Post Helpful? 1
  • +
  • -

#3 RPDK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 11-February 10

Re: Input Validation

Posted 14 February 2010 - 10:06 AM

I hope it looks a bit better now :blush:

Thanks japanir, the above code works like a charm :bigsmile:

I'm just going to implement my 'X and cancel button handling code'
in order to prevent the NullPointerException when cancel or X is pressed.

do
{ 
    name = JOptionPane.showInputDialog(null, "Enter name ", "NAME INPUT", JOptionPane.INFORMATION_MESSAGE); 
    if (name == null ) 
    {  
	System.exit(0);
	flag1 = false; 
    } 
    else 
    { 
	flag1 = true; 
    } 
} while(!flag1);


Going to work on the age validation now.

This post has been edited by RPDK: 14 February 2010 - 10:09 AM

Was This Post Helpful? 0
  • +
  • -

#4 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 485
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Input Validation

Posted 14 February 2010 - 10:47 AM

This doesn't really affect your code very much, but
if (name == null ) 
    {  
        System.exit(0); //you terminate the program here
        flag1 = false;  //this line is never reached!
    }

Was This Post Helpful? 1
  • +
  • -

#5 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 497
  • View blog
  • Posts: 1,453
  • Joined: 19-October 09

Re: Input Validation

Posted 14 February 2010 - 11:03 AM

What you would need to use for the age validation is the Calendar Class.

You would have to use the following,

  
 Calendar rightNow = Calendar.getInstance();



which would return a Calendar object that has been initialized with the current date and time of your machine.

what i would then recommend is creating 3 variables called day, month and year. You would then need to use the get method to retrieve each date type such as day, month and year

/*method returns Year and assigns to variable year*/
int year = c.get(Calendar.YEAR); 
/*method returns Month and assigns to variable month*/
int month = c.get(Calendar.MONTH) ; // 
/*method returns Day and assigns to variable day*/
int day = c.get(Calendar.DATE); //int day is calendar day//




As for the data validation.. it would be best to implement these :

If date entered is higher than current Date.

If day entered is 31 but it is month is April and April has 30 days.

Try having a look at all the possible wrong dates and ways of creating validation techniques to your code eliminate these.

Hope this helps you :)
Was This Post Helpful? 0
  • +
  • -

#6 RPDK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 11-February 10

Re: Input Validation

Posted 14 February 2010 - 12:10 PM

View Posterik.price, on 14 February 2010 - 09:47 AM, said:

This doesn't really affect your code very much, but
if (name == null ) 
    {  
        System.exit(0); //you terminate the program here
        flag1 = false;  //this line is never reached!
    }


You are right thanks :)

I managed to validate both name and age using japanir's code, everything is working perfectly!

Are there any methods or classes that would allow me to check the vowels and consonants in the name input?
I'd like to generate an error message if every 4 consonants there's no vowel or if every 3 vowels
there's no consonant in order to prevent names like 'Asdfdsf".
Was This Post Helpful? 0
  • +
  • -

#7 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1011
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Input Validation

Posted 14 February 2010 - 12:56 PM

Yeah there is way.
I posted a snippet doing that exact thing on DIC, However the Java code snippets page is broken...

You can do it manually:
pseufo code:
loop a String
if the current char is 'a', 'e', 'u', 'i' 'o' its a vowel
esle, obviously, no :)

**Edited,
The problem with the snippet page is solved, so here is the snippet:
http://www.dreaminco...snippet4522.htm

This post has been edited by japanir: 14 February 2010 - 04:47 PM

Was This Post Helpful? 1
  • +
  • -

#8 RPDK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 11-February 10

Re: Input Validation

Posted 15 February 2010 - 07:16 AM

Your snippet is working great japanir, however I'm having a difficult time checking
the vowels and/or the consonants.

I mean, I do get the total number of the vowels and consonants in the name string
but I can't find a way to check whether or not there are 3 vowels or 4 consonants in a row...

edit: typo

This post has been edited by RPDK: 15 February 2010 - 07:17 AM

Was This Post Helpful? 0
  • +
  • -

#9 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1011
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Input Validation

Posted 15 February 2010 - 07:59 AM

Well my snippet only count vowels in a given string.
You can alter it to suit your needs (this method checks if you have more than four vowels in a row)
it will return true if there are 4 vowels in arow,.
else it returns false.

public boolean fourVowelsInRow(String text) {
    int count = 0; // start the count at zero
    text = text.toLowerCase();
  
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
            count++;
            if(count >= 4){
                  return true;
            }
        }
        else count = 0;
    }

    return false;
}


Was This Post Helpful? 1
  • +
  • -

#10 RPDK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 11-February 10

Re: Input Validation

Posted 15 February 2010 - 08:12 AM

View Postjapanir, on 15 February 2010 - 06:59 AM, said:

Well my snippet only count vowels in a given string.
You can alter it to suit your needs (this method checks if you have more than four vowels in a row)
it will return true if there are 4 vowels in arow,.
else it returns false.

public boolean fourVowelsInRow(String text) {
    int count = 0; // start the count at zero
    text = text.toLowerCase();
  
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
            count++;
            if(count >= 4){
                  return true;
            }
        }
        else count = 0;
    }

    return false;
}




Thanks a million! Your code works like charm as usual :bigsmile:

I was trying to add the
for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
            count++;


in my name loop instead of the vowelcount method and things were getting messed up.

Thank you once again :bigsmile:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1