简体   繁体   English

防止字符串在Java中获取整数值

[英]Preventing a String from getting integer values in Java

Is there a possible way to do that? 有没有办法做到这一点?

eg In my application form a have a field for the user's name which is a String . 例如,在我的应用程序表单中,有一个用户名字段,它是String But how can I disallow the user from giving for example "L3bron James" instead of giving "Lebron James" ? 但是,如何禁止用户提供“ L3bron James”而不是“ Lebron James”

String sql_name = name.getText();
// name is a JTextField
if (sql_name.length() == 0)
    {
        //how to check if the name does not contain int digits
    JOptionPane.showMessageDialog(null,"Name is a string ,NOT an Integer, not a null value!!","Invalid Name",JOptionPane.ERROR_MESSAGE);
    }

You can use a regular expression on the string to see if it contains number characters: 您可以在字符串上使用正则表达式以查看其是否包含数字字符:

if (Pattern.compile("[0-9]").matcher(sql_name).find()) {
    // Show error message
}

It depends on where you want to filter for integers. 这取决于您要在哪里过滤整数。 Following this answer How to filter string for unwanted characters using regex? 按照此答案如何使用正则表达式过滤字符串中不需要的字符? you can use regex to check for integers and prompt the user again if you found an integer. 您可以使用正则表达式检查整数,如果找到整数,则再次提示用户。 Or you could just replace them which would be kind of rude. 或者,您也可以替换它们,这很粗鲁。

You can use StringUtils.isAlphaSpace from apache commons 您可以从Apache Commons使用StringUtils.isAlphaSpace

StringUtils.isAlphaSpace(null)   = false
StringUtils.isAlphaSpace("")     = true
StringUtils.isAlphaSpace("  ")   = true
StringUtils.isAlphaSpace("abc")  = true
StringUtils.isAlphaSpace("ab c") = true
StringUtils.isAlphaSpace("ab2c") = false
StringUtils.isAlphaSpace("ab-c") = false

Alternative Solution 替代解决方案

boolean flag = false;
for (int i = 0; i < sql_name.length(); i++) {
        if (Character.isDigit(sql_name.charAt(i)))
                flag = true;// number exists in the string
            }
if (flag == true)
   JOptionPane.showMessageDialog(null,"Name is a string ,NOT an Integer, NOT a null value!!","Invalid Name",JOptionPane.ERROR_MESSAGE);

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

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