gpt4 book ai didi

java - 验证字符串(PPS 编号)

转载 作者:行者123 更新时间:2023-11-29 07:05:25 31 4
gpt4 key购买 nike

好的,我正在尝试验证一个字符串(在本例中为 PPS 编号)。我似乎无法让它正常工作。

问题是:

Each Irish citizen is allocated a PPS number once they reach the age of 18 that is unique to them and used for taxation purposes. A valid PPS number will have exactly 8 or 9 characters in total. It will begin with exactly 7 digits and end with one or two uppercase letters. So, for example, 1234567A would be considered a valid PPS number, as would 7863456RT, but 6478TY*%& and 8768086b would both be considered invalid PPS numbers.

package Assess2013Two;
import java.util.Scanner;
public class Group3Solution {
public static void main(String[] args)
{
int index = 0;
char ch;
Scanner input = new Scanner(System.in);

System.out.print("Please enter your PPS number: ");
String ppsNumber = input.nextLine();

if(ppsNumber.length() >= 8 && ppsNumber.length() <= 9){
if(ppsNumber.charAt(7) >= 'A' && ppsNumber.charAt(7) <= 'Z' && ppsNumber.charAt(8) >= 'A' && ppsNumber.charAt(8) <= 'Z')
{
if(ppsNumber.length() == 8) {
ch = ppsNumber.charAt(index);
while(index < ppsNumber.length() && ch >= '0' && ch <= '9'){
index++;
if(index < ppsNumber.length())
ch = ppsNumber.charAt(index);
}
if(index == ppsNumber.length())
System.out.println("You entered a valid PPS number.");
else
System.out.println("Invalid PPS number!! At least one of the first 7 characters were not digits.");
}else {
ch = ppsNumber.charAt(index);
while(index < ppsNumber.length()-2 && ch >= '0' && ch <= '9'){
index++;
if(index<ppsNumber.length()-2)
ch = ppsNumber.charAt(index);
}
if(index == ppsNumber.length()-2)
System.out.println("You entered a valid PPS number.");
else
System.out.println("Invalid PPS number!! At least one of the first 7 characters were not digits.");
}


}else
System.out.println("Invalid PPS number!! The second-last or last, or both, were not uppercase letters");
}else
System.out.println("Invalid PPS number!! It must contain at least 8 to 9 characters.");

input.close();
}
}

最佳答案

对于这些类型的问题,我更喜欢使用正则表达式。

if(ppsNumber.matches("\\d{7}[A-Z]{1,2}"))
{
// valid
}
else
{
//invalid
}

关于java - 验证字符串(PPS 编号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20385963/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com