Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem lies in the if statement:</p> <pre><code>for (int pass=1; pass &lt; n; pass++){ for (int i=0; i &lt; n-pass; i++) { if(players[i].getLastName().compareTo(players[i + 1].getLastName()) &gt; 0) temp = players[i]; players[i] = players[i+1]; players[i+1] = temp; } } </code></pre> <p>If, in the first pass (i.e. i == 0, the compareTo method returns a value equal to or less than 0, the statement assigning temp a pointer to element 0 of the players array will not execute, temp will have a null pointer and the next two lines, not conditionally executed in the scope of the if statement, will assign element 1 to element 0 of the players array and a null pointer to element 1. </p> <p>On the next pass (i.e. i == 1), this will then result in a java.lang.NullPointerException because now, the players[1] element has a null pointer from the first pass. </p> <p>Depending on the order of names input, the exception might or might not be thrown if, on the first pass, the compareTo method returns a value > 0. From that point on, temp will have a valid pointer but whatever it points to will get swapped with the i+1th element even if it is not pointing to the ith element. The array's name contents will likely get mangled because the name sawp will not occur as desired.</p> <p>Fixing the code segment to read:</p> <pre><code>for (int pass=1; pass &lt; n; pass++) { for (int i=0; i &lt; n-pass; i++) { if(players[i].getLastName().compareTo(players[i + 1].getLastName()) &gt; 0) { temp = players[i]; players[i] = players[i+1]; players[i+1] = temp; } } } </code></pre> <p>will cure the problem and also have a better indentation practice. </p> <p>One visible indicator of the problem is that the indentation in your sample, although not normal practice for if and for scopes, still indicates that only the first line of the array element swap is in the scope of the if statement instead of all three lines. </p> <p>If scope mistakes are a common root of software errors. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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