Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with all the performance and readability posts. However, there are cases where it really does matter. A couple other people mentioned this, but it might be easier to see with examples.</p> <p>Consider this slightly modified example:</p> <pre><code>public static void main(String[] args) { String[] myNumberStrings = new String[] {"1.2345", "asdf", "2.3456"}; ArrayList asNumbers = parseAll(myNumberStrings); } public static ArrayList parseAll(String[] numberStrings){ ArrayList myFloats = new ArrayList(); for(int i = 0; i &lt; numberStrings.length; i++){ myFloats.add(new Float(numberStrings[i])); } return myFloats; } </code></pre> <p>If you want the parseAll() method to return null if there are any errors (like the original example), you'd put the try/catch on the outside like this:</p> <pre><code>public static ArrayList parseAll1(String[] numberStrings){ ArrayList myFloats = new ArrayList(); try{ for(int i = 0; i &lt; numberStrings.length; i++){ myFloats.add(new Float(numberStrings[i])); } } catch (NumberFormatException nfe){ //fail on any error return null; } return myFloats; } </code></pre> <p>In reality, you should probably return an error here instead of null, and generally I don't like having multiple returns, but you get the idea.</p> <p>On the other hand, if you want it to just ignore the problems, and parse whatever Strings it can, you'd put the try/catch on the inside of the loop like this:</p> <pre><code>public static ArrayList parseAll2(String[] numberStrings){ ArrayList myFloats = new ArrayList(); for(int i = 0; i &lt; numberStrings.length; i++){ try{ myFloats.add(new Float(numberStrings[i])); } catch (NumberFormatException nfe){ //don't add just this one } } return myFloats; } </code></pre>
 

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