Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try introducing the Apache's "<a href="http://commons.apache.org/lang/" rel="nofollow noreferrer">commons Lang</a>" library into your project and for your last line you can do</p> <pre><code>int aInt = 0; if(StringUtils.isNotBlank(aString) &amp;&amp; StringUtils.isNumeric(aString) ){ aInt = Integer.parseInt(aString); } </code></pre> <p>edit: Not sure why the downvote. The JtextField will take any string. If the text field is listening on each key press, every non-numeric value (including blank) that is entered will generate the NumberFormatException. Best to check if it is Numeric before doing anything with the new value.</p> <p>edit2: As per Thomas' comments below. I ran a test to compare the try/catch vs the StringUtils way of solving this issue. The test was ran 5million times for each. The average time for the try/catch was 21 seconds. The average time for the StringUtils was 8 seconds. So using StringUtils for heavy load is considerably faster. If the load on the code is small you will notice little to no difference. The test ran was</p> <pre><code>try{ result = Integer.parseInt(num); }catch(NumberFormatException ex){ result = -1; } </code></pre> <p>vs</p> <pre><code>if(StringUtils.isNotBlank(num) &amp;&amp; StringUtils.isNumeric(num)){ result = Integer.parseInt(num); }else{ result = -1; } </code></pre> <p>each loop through generated a new random string of 10 digits to avoid any optimization in the loops on the if statement. This added 6-7 seconds of overhead.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload