【发布时间】:2021-07-26 02:43:06
【问题描述】:
在名为 Source 的类中创建以下公共静态方法:
checkRegistrationNumber(String):int
输入参数是车辆登记号,输出是 -1、0 或 1,基于以下给定规则。 如果车辆登记号按照以下格式有效,则该方法应返回 0,否则返回 -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.
在Source类的main方法中做如下操作
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时,它显示无效,即使它是幸运的。数字。 它不能正常工作。
【问题讨论】:
-
DL10G4839甚至没有通过[(KA)(DL)][(0[1-9])(10)][A-Z]{1,2}[1-9]\\d{3}测试 regex101.com/r/KARISl/1 -
由于无论如何您都需要提取单个值,因此您可以完全放弃正则表达式。而是根据您给定的模式解析字符串。此外,您的正则表达式甚至无法在没有错误的情况下编译。就连
[(KA)(DL)]这个部分都已经错了。 -
这应该是你的正则表达式:
(KA|DL)(10|0[1-9])([A-Z]{1,2})([1-9][0-9]{3}) -
@SkillGG 您可能应该添加字符串锚点的开头和结尾;)