我已经修复了我以前的代码问题,现在我希望它识别它是 4 位数字还是更少或 6 位及以上,并带有"Else if"。
当我输入字母以在"Else if"中使用System.out.println拒绝它时。
String digit;
String regex;
String regex1;
regex = "[0-9]{5}";
String test;
String validLength = "5";
char one, two, three, four, five; {
System.out.println("In this game, you will have to input 5 digits.");
do {
System.out.println("Please input 5-digits.");
digit = console.next();
test = digit.replaceAll("[a-zA-Z]", "");
if (digit.matches(regex)) {
one = (char) digit.charAt(0);
two = (char) digit.charAt(1);
three = (char) digit.charAt(2);
four = (char) digit.charAt(3);
five = (char) digit.charAt(4);
System.out.println((one + two + three + four + five) / 2);
}
这个正则表达式应该符合你的需要(前导零):
[0-9]{5}
您将使用 while 循环,循环直到满足这两个条件,例如
while (!inputString.matches("[0-9]{5}")) {
// ask again and again
if (!isInteger(inputString)) {
// invalid input
} else {
if (inputString.length() < 5) {
// too low
} else if (inputString.length() > 5) {
// too high
}
}
}
您可以使用如下所示的帮助程序方法:
public boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}