0

我有一个可以读取 7 个字符的字母数字代码(由用户输入)的扫描仪。字符串变量称为“代码”。

代码的最后一个字符(第 7 个字符,第 6 个索引)必须是数字,其余的可以是数字或字母。

所以,我试图做一个 catch,如果代码中的最后一个字符不是数字(从 0 到 9),它将停止执行该方法的其余部分。

但是,我的代码没有按预期工作,即使我的代码以 0 到 9 之间的整数结尾,也会满足 if 语句,并打印出“代码中的最后一个字符是非数字的”。

示例代码:45m4av7

CharacterAtEnd 打印出字符串字符 7,这是应该的。但是我的程序仍然告诉我我的代码以非数字方式结束。我知道我的数值是字符串字符,但这不重要,不是吗?我也显然无法将实际整数值与“|”进行比较,这主要是我使用 String.valueOf 并采用 0-9 的字符串字符的原因。

String characterAtEnd = String.valueOf(code.charAt(code.length()-1));
System.out.println(characterAtEnd);

 if(!characterAtEnd.equals(String.valueOf(0|1|2|3|4|5|6|7|8|9))){
     System.out.println("INVALID CRC CODE: last character in code in non-numerical.");
     System.exit(0);

我一生都无法弄清楚为什么我的程序告诉我我的代码(末尾有 7)以非数字方式结束。它应该跳过 if 语句并继续。正确的?

4

2 回答 2

0

您在这里进行按位运算: if(!characterAtEnd.equals(String.valueOf(0|1|2|3|4|5|6|7|8|9)))

|查看和之间的区别||

这段代码应该使用正则表达式完成您的任务:

String code = "45m4av7";

if (!code.matches("^.+?\\d$")){
    System.out.println("INVALID CRC CODE");
}

此外,作为参考,此方法有时在类似情况下会派上用场:

/* returns true if someString actually ends with the specified suffix */
someString.endsWith(suffix);

由于.endswith(suffix)不采用正则表达式,如果您想遍历所有可能的小写字母值,则需要执行以下操作:

/* ASCII approach */
String s = "hello";
boolean endsInLetter = false;
for (int i = 97; i <= 122; i++) {
    if (s.endsWith(String.valueOf(Character.toChars(i)))) {
        endsInLetter = true;
    }
}
System.out.println(endsInLetter);

/* String approach */
String alphabet = "abcdefghijklmnopqrstuvwxyz";
boolean endsInLetter2 = false;
for (int i = 0; i < alphabet.length(); i++) {
    if (s.endsWith(String.valueOf(alphabet.charAt(i)))) {
        endsInLetter2 = true;
    }
}
System.out.println(endsInLetter2);

请注意,上述方法都不是一个好主意——它们笨重而且效率很低。

脱离 ASCII 方法,您甚至可以执行以下操作:

ASCII 参考:http ://www.asciitable.com/

int i = (int)code.charAt(code.length() - 1);

/* Corresponding ASCII values to digits */
if(i <= 57 && i >= 48){
    System.out.println("Last char is a digit!");
}

如果您想要单线,请坚持使用正则表达式,例如:

System.out.println((!code.matches("^.+?\\d$")? "Invalid CRC Code" : "Valid CRC Code"));

我希望这有帮助!

于 2013-06-04T00:48:00.053 回答
0

String contains方法将在这里工作:

String digits = "0123456789";
digits.contains(characterAtEnd); // true if ends with digit, false otherwise

String.valueOf(0|1|2|3|4|5|6|7|8|9)实际上是"15",当然不可能等于最后一个字符。这应该是有道理的,因为0|1|2|3|4|5|6|7|8|9使用整数数学计算为 15,然后将其转换为字符串。

或者,试试这个:

String code = "45m4av7";
char characterAtEnd = code.charAt(code.length() - 1);
System.out.println(characterAtEnd);

if(characterAtEnd < '0' || characterAtEnd > '9'){
    System.out.println("INVALID CRC CODE: last character in code in non-numerical.");
    System.exit(0);
}
于 2013-06-04T00:34:32.920 回答