Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The first one will give you an ArrayIndexOutOfBoundsException because i is never actually reset to 0.</p> <p>The second one will (probably) give you an overflow error (or related undesirable effect) when i == Integer.MAX_VALUE (which might not actually happen in your case, but isn't good practice, IMHO).</p> <p>So I'd say the second one is "more correct", but I would use something like:</p> <pre><code>i = (i+1) % buffer.length; return i; </code></pre> <p>Which I think has neither of the two problems.</p> <p>I went ahead and tested everyone's code, and was sad to find that only one of the previous posts (at the time of this post's writing) works. (Which one? Try them all to find out! You might be surprised!)</p> <pre><code>public class asdf { static int i=0; static int[] buffer = {0,1,2}; public static final void main(String args[]){ for(int j=0; j&lt;5; j++){ System.out.println(buffer[getIndex()]); } } public static int getIndex(){ // return (++i == buffer.length) ? 0: i; // return ++i % buffer.length; // i = (i++ == buffer.length) ? 0 : i; // return i; // i++; // if (i &gt;= buffer.length) // { // i = 0; // } // return i; // return (i+1 == buffer.length) ? 0 : i+1; i = (i+1) % buffer.length; return i; } } </code></pre> <p>Expected output is: 1 2 0 1 2</p> <p>Apologies in advance if there's a coding error on my part and I accidentally insult someone! x.x</p> <p>PS: +1 for the previous comment about not using post-increment with equality checks (I can't actually upmod posts yet =/ )</p>
    singulars
    1. This table or related slice is empty.
    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.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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