简体   繁体   English

如何检查Java中的文本字段是否为空并包含整数值?

[英]How to check if a text field is not empty in Java & contains Integer value?

I have a GUI which stores the Bank Account number, during validation, I need to check if the user has entered the account number.我有一个存储银行帐号的 GUI,在验证期间,我需要检查用户是否输入了帐号。

For string fields, isEmpty() method can be used, but what about Integer field account number.对于字符串字段,可以使用 isEmpty() 方法,但是对于整数字段帐号呢?

Integer.parseInt(jTextField1.getText()).isEmpty()

would give an error, How to check for null fields when its an Integer?会给出一个错误,当它是一个整数时如何检查空字段?

Check is Empty before parsing it into integer like在将其解析为整数之前检查为空

if(!jTextField1.getText().isEmpty()){

Integer.parseInt(jTextField1.getText());

}

You should rather try the following code你应该试试下面的代码

if(!(jTextField1.getText().isEmpty()))
    {
        int accountNumber=Integer.parseInt(jTextField1.getText());
    }

Class Integer is just an wrapper on top of primitive int type. Integer类只是原始int类型之上的一个包装器。 So it can either be null or store a valid integer value.因此它可以为null或存储一个有效的整数值。 There is no obvious "empty" definition for it.它没有明显的“空”定义。

If you just compare Integer against empty String , you''ll get false as a result.如果您只是将Integer与空String进行比较,您将得到false结果。 Always.总是。 See Integer.equals(Object o) implementation:参见Integer.equals(Object o)实现:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

First of all, you can get a NumberFormatException during parsing integer in the line:首先,您可以在解析行中的整数期间获得NumberFormatException

Integer accountNumber = Integer.parseInt(jTextField1.getText())

And you are getting it, since For input string: "" looks like a NumberFormatExpection message.你明白了,因为For input string: ""看起来像一个NumberFormatExpection消息。

In your example you should either check whether the "accountNumber" attribute value is a number (assume it's a string) and then parse it, or parse it as is and catch NumberFormatException that Integer.parseInt() throws on incorrect argument.在您的示例中,您应该检查"accountNumber"属性值是否是一个数字(假设它是一个字符串)然后解析它,或者按原样解析它并捕获Integer.parseInt()在不正确的参数上抛出的NumberFormatException

First solution:第一个解决方案:

if(!jTextField1.getText().isEmpty() && jTextField1.getText().matches("\\d+")){ //null-check and regex check to make sure the string contains only 
     Integer accountNumber = Integer.parseInt(jTextField1.getText());                 
}

Second solution:第二种解决方案:

try{
     Integer accountNumber = Integer.parseInt(jTextField1.getText());                 
}catch (NumberFormatException e) {
// handle error

} }

Hope this should help you.希望这对你有帮助。

PS If you use Java of version 7 or higher, consider use try-with-resources to manage Connection and PreparedStatement . PS 如果您使用 Java 7 或更高版本,请考虑使用try-with-resources来管理ConnectionPreparedStatement

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

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