Friday, 14 February 2020

Validation whether a string has only lower and upper case alphabets using regular expressions in java

String st="abcd#adl#lavjkllads";
st.matches("[a-z]*[A-Z]*");

but this will not take spaces into consideration

SO WE USE st.matches("[a-z A-Z]*");

Example Program
Develop a program to create a class "Dictionary" that contains the following information a)Name of a person b)Mobile number. The setter method raise an exceptions when name has any other characters apart from lower and upper case alphabets and when mobile number is negative or does not have 10 digits. The parameterized constructor calls the setter and throws the Exceptions. The main() method of DictionaryDemo must handle the exceptions.

package parent;

import java.util.Scanner;

class InvalidName extends RuntimeException
{
InvalidName(String st)
{
super(st);
}
}
class InvalidMobile extends RuntimeException
{
InvalidMobile(String st)
{
super(st);
}
}
class Dictionary
{
private String name;
private long mobile;
Dictionary(String name, long mobile)
{
if(setName(name) == false)
throw new InvalidName("Not a valid name");
if(setMobile(mobile) == false)
throw new InvalidMobile("Not a valid mobile number");
}
public boolean setName(String name)
{
if(name.matches("[a-z A-Z]*"))
{
this.name = name;
return true;
}
return false;
}

public boolean setMobile(long mobile)
{

if(mobile >=1000000000L && mobile <= 9999999999L)
{
this.mobile=mobile;
return true;
}
return false;
}
}
public class DictionaryDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter name and mobile number");
try
{
Dictionary ob = new Dictionary(sc.next(),sc.nextLong());
}
catch(InvalidName e)
{
e.printStackTrace();
}
catch(InvalidMobile e)
{
e.printStackTrace();
}
}

}

No comments:

Post a Comment