Greetings,
I'm trying to validate whether my integer is null. If it is, I need to prompt the user to enter a value. My background is Perl, so my first attempt looks like this:
int startIn = Integer.parseInt (startField.getText()); if (startIn) { JOptionPane.showMessageDialog(null, "You must enter a number between 0-16.","Input Error", JOptionPane.ERROR_MESSAGE); }
This does not work, since Java is expecting boolean logic.
In Perl, I can use "exists" to check whether hash/array elements contain data with:
@items = ("one", "two", "three"); #@items = (); if (exists($items[0])) { print "Something in \@items.\n"; } else { print "Nothing in \@items!\n"; }
Is there a way to this in Java? Thank you for your help!
Jeremiah
P.S. Perl exists info.
Primitive data type int can not be checked for a null value.
To check if a string is null or empty in Java, use the == operator.
null is Case sensitive: null is literal in Java and because keywords are case-sensitive in java, we can't write NULL or 0 as in C language.
parseInt()
is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers
, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
Integer s = null; try { s = Integer.valueOf(startField.getText()); } catch (NumberFormatException e) { // ... } if (s != null) { ... }
Beware if you do decide to use parseInt()
! parseInt()
doesn't support good internationalization, so you have to jump through even more hoops:
try { NumberFormat nf = NumberFormat.getIntegerInstance(locale); nf.setParseIntegerOnly(true); nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at. // Start parsing from the beginning. ParsePosition p = new ParsePosition(0); int val = format.parse(str, p).intValue(); if (p.getIndex() != str.length()) { // There's some stuff after all the digits are done being processed. } // Work with the processed value here. } catch (java.text.ParseFormatException exc) { // Something blew up in the parsing. }
Try this:
Integer startIn = null; try { startIn = Integer.valueOf(startField.getText()); } catch (NumberFormatException e) { . . . } if (startIn == null) { // Prompt for value... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With