提问者:小点点

爪哇车辆登记号码验证器[副本]


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.
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

我试过这个密码。

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");
    }
 }
}

但在检查DL10G4839时,即使是幸运标志,也显示无效。号码。它不能正常工作。


共1个答案

匿名用户

您的正则表达式是错误的!

如果要检查本练习中的约束,则应使用以下regex:

"^(KA|DL)(10|0[1-9])([A-Z]{1,2})([1-9][0-9]{3})$"

说明:

^ # start of the string
( # open first group
KA|DL # find KA or DL
) # close first group
( # second group
10| # 10 literally or
0[1-9] # numbers from 01 to 09
) # close second group
( # third group
[A-Z]{1,2} # one or two A-Z (uppercase)
) # close third group
( # open fourth group
[1-9][0-9]{3} # numbers from 1000 to 9999
) # close fourth group
$ # end of the string
"^(?:KA|DL)(?:10|0[1-9])[A-Z]{1,2}[1-9][0-9]{3}$"