【问题标题】:Make java check the line entered to see if it is only letters. [duplicate]让java检查输入的行是否只有字母。 [复制]
【发布时间】:2013-10-20 10:18:50
【问题描述】:

我对 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);

这显然是行不通的,因为它只是定义输入只能包含字符 a-z,我希望有一种方法来告诉它它只能包含字母,但还没有弄清楚如何。

任何帮助都将不胜感激,即使是指向我可以阅读正确命令并自己弄清楚的链接:)

谢谢

【问题讨论】:

标签: java


【解决方案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]+");
}

【讨论】:

  • 谢谢你的回答:)
【解决方案2】:

你可以使用一个简单的正则表达式

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

【讨论】:

  • 非常感谢 :) 现在感觉就像我正在尝试用一种新的语言表达自己,我知道我想说什么但找不到单词 :)
【解决方案3】:
while (scanner.hasNext()) {
    String word = scanner.next();
    for (int i = 0; i < word.length; i++) {
        if (!Character.isLetter(word.charAt(i))) {
            // do something
        }
    }
}

【讨论】:

  • 谢谢你的回答:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2014-10-19
相关资源
最近更新 更多