簡體   English   中英

防止字符串在Java中獲取整數值

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

有沒有辦法做到這一點?

例如,在我的應用程序表單中,有一個用戶名字段,它是String 但是,如何禁止用戶提供“ 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);
    }

您可以在字符串上使用正則表達式以查看其是否包含數字字符:

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

這取決於您要在哪里過濾整數。 按照此答案如何使用正則表達式過濾字符串中不需要的字符? 您可以使用正則表達式檢查整數,如果找到整數,則再次提示用戶。 或者,您也可以替換它們,這很粗魯。

您可以從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

替代解決方案

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