【问题标题】:Allow a jTextField to be blank?允许 jTextField 为空?
【发布时间】:2016-11-08 18:57:00
【问题描述】:

我创建了一个简单的应用程序,用户在其中输入两个值并自动用答案更新文本字段并检查输入是否为数字。

检查用户输入的代码(来自这个问题:How to Auto Calculate input numeric values of Text Field in JAVA)如下:

private boolean isDigit(String string) 
{
    for (int n = 0; n < string.length(); n++) 
    {
        //get a single character of the string
        char c = string.charAt(n);

        if (!Character.isDigit(c)) 
        {
            //if its an alphabetic character or white space
            return false;
        }
    }
    return true;
}

它可以工作,但是当文本字段为空白时,会出现以下错误消息:java.lang.NumberFormatException: For input string: ""

如何更改我使用的代码,以便可以接受空白文本字段并且不会产生错误?

【问题讨论】:

标签: java swing netbeans jtextfield


【解决方案1】:

您可以在开始时添加if 以检查字符串是否合法

private boolean isDigit(String string) 
{
    if(string == null || string.isEmpty()) {
        return false;
    }

    for (int n = 0; n < string.length(); n++) 
    {
        //get a single character of the string
        char c = string.charAt(n);

        if (!Character.isDigit(c)) 
        {
            //if its an alphabetic character or white space
            return false;
        }
    }
    return true;
}

【讨论】:

    【解决方案2】:

    您不能将 isDigit() 应用于空字符串或空格。 在继续执行逻辑之前,您可以使用“if”条件来检查字符串是否为空,如下所示:

    private boolean isDigit (String string) {
           if (string.length()>=1) {
                  for (int n = 0; n < string.length(); n++) { 
                         //logic
                  }
           }else { 
                  return false;
           }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-04
      • 2013-12-30
      • 2021-12-30
      • 2018-01-12
      • 2013-01-22
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      相关资源
      最近更新 更多