【发布时间】:2020-03-19 22:36:33
【问题描述】:
我正在尝试验证用户输入的字符串。用户必须输入一个 7 个字符的字符串;字符串前 3 个字符必须是字母,后 4 个字符必须是数字。
我写了这段代码(作为一个方法),但由于某种原因,它接受第一个字符作为数字(它应该是一个字母),其余的都是数字。例如:
Please enter word : **1gy2345**
这将根据需要进入循环,然后进入 main 中的下一个方法。
如果用户输入一个长度大于 7 的单词,它会要求他输入一个有效的单词。
例如:
Please enter word : **bob12345**
The word entered is invalid. Please enter a word beginning with 3 letters and ending with 4 numbers ( The word must be 7 characters long ).
这是我的代码:
public static final String solicitationMessage = " Please enter word ";
public static final String errorMessage = " The word entered is invalid. Please enter a word beginning with 3 letters and ending with 4 numbers ( The word must be 7 characters long ).
public static final int lengthOfString = 7;
public static String validateString(String solicitationMessage, String errorMessage, int lengthOfString) {
System.out.print(solicitationMessage);
String word = keyboard.nextLine();
while (!( word.length() == lengthOfString )) {
if (((word.charAt(0) <= 'a' || word.charAt(0) >= 'z') || (word.charAt(1) <= 'a' || word.charAt(1) >= 'z')
|| (word.charAt(2) <= 'a' || word.charAt(2) >= 'z'))) {
System.out.print(errorMessage);
System.out.print(solicitationMessage);
word = keyboard.nextLine();
}
}
return word;
}
但是,如果我输入一个高于 7 个限制字符的字符串,它会再次要求我输入一个有效的字符串,就像它应该做的那样。
不允许使用正则表达式。
有什么帮助吗?
【问题讨论】:
-
你只输入长度不是7的循环,所以任何长度为7的字符串都被认为是有效的,例如
!@#$%^&会起作用。 -
另外,您可能希望将
<=比较更改为<- 因为您希望将a和z视为字母。