You need to use an index that is limited by the size of the array. More precisely, and esoterically, you need to match the for-loop iterations {0..9} with the actual indices for the flame array {0 .. flames.length() - 1 }, which are the same in this case, {0..5}.
When the loop repeats from 0 to 5, the mapping is trivial. When the loop repeats for the 6th time, you need to map it to the index of array 0, when it iterates to the seventh time, you map it to index of array 1, etc.
== Naive way ==
for(int z = 0, j = 0; z < ctr-1; z++, j++) { if ( j >= flames.length() ) { j = 0;
== More appropriate way ==
You can then clarify this by realizing that flames.length() is the invariant that you exit the for loop.
final int n = flames.length(); for(int z = 0, j = 0; z < ctr-1; z++, j++) { if ( j >= n ) { j = 0;
== How to do it ==
Now, if you pay attention, you can see that we are just doing modular index arithmetic. So, if we use the modular (%) operator, we can simplify your code:
final int n = flames.length(); for(int z = 0; z < ctr-1; z++) { res = (flames[z % n]); jLabel1.setText(String.valueOf(res)); }
When dealing with similar problems, consider mapping functions from a domain (in this case, for loop iterations) to a range (valid array indices).
More importantly, work it out on paper before you start the code. It will take a long time to solve these types of elementary problems.
luis.espinal
source share