I have a GUI which stores the Bank Account number, during validation, I need to check if the user has entered the account number.
For string fields, isEmpty() method can be used, but what about Integer field account number.
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. So it can either be null
or store a valid integer value. There is no obvious "empty" definition for it.
If you just compare Integer
against empty String
, you''ll get false
as a result. Always. See Integer.equals(Object o)
implementation:
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:
Integer accountNumber = Integer.parseInt(jTextField1.getText())
And you are getting it, since For input string: ""
looks like a NumberFormatExpection
message.
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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.