In the class named Source create the following public static method:
checkRegistrationNumber(String):int
The input parameter is a vehicle registration number and the output is -1, 0 or 1 based on below given rules. If the Vehicle registration number is valid as per the below format the method should return 0, else -1
PPXXQQYYYY
PP - Should be either KA or DL
XX - Number from 01 to 10
QQ - 1 or 2 alphabets from A-Z(uppercase)
YYYY - Number from 1000 to 9999
Ex: KA01MG2323, DL10G5454
Method should return 1, if the registration number is valid, and last 4 digits add up to a lucky number.
When last 4 digits are repeatedly added(see below) and the sum is 6, it is a lucky number
KA01MG8484
8+4+8+4 = 24 -> 2 + 4 = 6 (Lucky number)
if the input string is empty or null, the method should return -1.
Do the following in the main method of Source class
Accept Registration number from the console
If the Registration number is invalid, display Invalid registration number
If the Registration number is valid but not lucky, display Valid registration number
If the Registration number is valid and lucky, display Lucky registration number
I tried this code.
import java.util.*;
import java.util.regex.*;
class Source
{
static int checkRegistrationNumber(String st){
String regex= "[(KA)(DL)][(0[1-9])(10)][A-Z]{1,2}[1-9]\\d{3}";
Pattern p=Pattern.compile(regex);
Matcher m = p.matcher(st);
if(m.find()){
String lastfour="";
lastfour = st.substring(st.length()-4);
int a = Integer.parseInt(lastfour);
int[] arr = new int[10];
int u = 1000;
for(int i=0;i<4;i++){
arr[i] =a/u;
a=a%u;
u=u/10;
}
int sum;
sum=arr[0]+arr[1]+arr[2]+arr[3];
if(sum>10){
int sum1=sum/10;
int sum2=sum%10;
int sum3= sum1+sum2;
if(sum3==6){
return 1;
}
else {
return 0;
}
}
else if(sum==6){
return 1;
}
else{
return 0;
}
}
else{
return -1;
}
}
public static void main(String[] args)
{
Scanner sc =new Scanner(System.in);
String str=sc.nextLine();
int n=checkRegistrationNumber(str);
if(n==1){
System.out.println("Lucky registration number");
}
else if(n==0){
System.out.println("Valid registration number");
}
else{
System.out.println("Invalid registration number");
}
}
}
but When checking DL10G4839, it is showing Invalid even it is lucky reg. number. it is not working properly.