我对Java很新,并且一直在尝试编写一些代码,因此它会检查收到的输入只是字母,因此不能放入特殊的字符或数字。
到目前为止,我已经走到了这一步
System.out.println("Please enter your first name");
while (!scanner.hasNext("a-z")
{
System.out.println("This is not in letters only");
scanner.nextLine();
}
String firstname = scanner.nextLine();
int a = firstname.charAt(0);
这显然不起作用,因为它只是定义输入只能包含字符az,我希望有一种方法告诉它它只能包含字母但是还没有弄清楚如何。
任何帮助都会受到赞赏,即使是我可以阅读正确命令的链接,也可以自己解决:)
由于
答案 0 :(得分:1)
您可以使用以下任何two methods:
public boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
public boolean isAlpha(String name) {
return name.matches("[a-zA-Z]+");
}
答案 1 :(得分:0)
您可以使用简单的正则表达式
System.out.println("Please enter your first name");
String firstname = scanner.nextLine(); // Read the first name
while (!firstname.matches("[a-zA-Z]+")) { // Check if it has anything other than alphabets
System.out.println("This is not in letters only");
firstname = scanner.nextLine(); // if not, ask the user to enter new first name
}
int a = firstname.charAt(0); // once done, use this as you wish
答案 2 :(得分:0)
while (scanner.hasNext()) {
String word = scanner.next();
for (int i = 0; i < word.length; i++) {
if (!Character.isLetter(word.charAt(i))) {
// do something
}
}
}