如何使用else-if语句检查输入中的最后8个字符是否为数字且不是零?Java



我正在尝试构建一个计算成绩的程序。其中一部分要求输入正确格式的学生ID(########(。我测试的错误是:;退出";?,第一个字符是"A"吗?,总长度是9个字符吗?,最后8个字符是数字吗?,和最后8位数字不是0。我算出了前三个,但我不知道如何检查后两个标准。我还需要包含NumberFormatException。我的代码目前还不能正常工作,但这就是我目前所拥有的:

public static String getStudentID(String sid) {
boolean goodval = false;
long snum = Long.parseLong(sid.substring(1));

do{
try{
if (sid.equals("quit")) {
goodval = true;
} else if (sid.charAt(0) != 'A') {
System.out.println("Student ID must start with 'A'");
goodval = false;
} else if (sid.length()!=9) {
System.out.println("Student ID must be 9 characters long");
goodval = false;
} else if (Long.parseLong(sid.substring(1))) {
goodval = false;
} else {
goodval = true;
}

} catch (NumberFormatException e){ 
System.out.println("The last part of the ID" + sid.substring(1) + " was not a number.");
sc.nextLine();
}
} while (goodval = false);
return sid;
}

此正则表达式应在一行中满足所有要求:[A] {1}\d{8}(?<!A000000000(|退出

在此处进行测试:http://regexstorm.net/tester?p=%5bA%5d%7b1%7d%5cd%7b8%7d%28%3f%3c!A000000000%29%7退出&i=A12345678

String类有一个方法调用length(),它返回一个表示字符串中字符数的整数。字符串的最后八个字符将被索引为length() - 1length() - 8

Character类有一个感兴趣的静态方法isDigit((,如果字符是数字,它将返回true

我不确定你想如何构建你的代码,但这里有一个例子,将为你分解备选方案。

for(int counter = 0; counter < sid.length(); counter++)
{
if(Character.isDigit(sid.charAt(counter))
{
if(sid.charAt(counter) == '0')
{
// it's a digit AND it's a zero
}
else
{
// it's a digit, but not a zero
}
}
else
{
// it's alpha or whitespace
}
}

相关内容

最新更新