简体   繁体   English

Java,字符串只接受字母和“if”语句

[英]Java, string to accept only letters and “if” statement

This is the code I have in a setName() method which I want to only accept letters (not digits)这是我在 setName() 方法中的代码,我只想接受字母(不是数字)

      playerName = ""; 
      if (playerName.isDigit)
      {System.out.println("Please enter letters only");
       } 

I am getting an error message which says "illegal parenthesised expression.我收到一条错误消息,上面写着“非法括号表达式。

String type doesn't have isDigit property. String类型没有isDigit属性。 Use the following code to check if your variable contains digits.使用以下代码检查您的变量是否包含数字。

if (playerName.matches(".*\\d+.*")) {
    System.out.println("Please enter letters only");
} 

This code will work for you:此代码将为您工作:

public static void setName ( String playerName ){
    if (playerName.matches(".*\\d.*") || playerName.isEmpty()) {
        System.out.println("Please enter letters only");
    } else {
        //Your code here
    }
}

You can use Lambda expression to check whether the input string contains only character or not.您可以使用Lambda expression来检查输入字符串是否仅包含字符。 In your setName() method, do the following在您的setName()方法中,执行以下操作

playerName="abcd";             //Take playerName from user input or as method argument

if(playerName==null || playerName.equals("") || !playerName.chars().allMatch(Character::isLetter))
        System.out.println("Please enter letters only");

else{

    //Do your work if someone enters name containing only letters.

}

There's no isDigit method in String.class in Java, but there're lots of ways to do it. Java 中的String.class中没有isDigit方法,但是有很多方法可以做到。

Take a look: https://mkyong.com/java/java-how-to-check-if-a-string-is-numeric/看看: https://mkyong.com/java/java-how-to-check-if-a-string-is-numeric/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM