Returning to the first index after reaching the last in the array

After my array in the for loop reaches the last index, I get an exception saying that the index is outside. I would like to return to the first index until z becomes equal to ctr . How can i do this?

My code is:

 char res; int ctr = 10 char[] flames = {'F','L','A','M','E','S'}; for(int z = 0; z < ctr-1; z++){ res = (flames[z]); jLabel1.setText(String.valueOf(res)); } 
+8
java arrays
source share
5 answers

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; // reset back to the beginning } res = (flames[j]); jLabel1.setText(String.valueOf(res)); } 

== 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; // reset back to the beginning } res = (flames[j]); jLabel1.setText(String.valueOf(res)); } 

== 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.

+4
source share

While luis.espinal answers in terms of efficiency, it is better, I think you should also look into Iterator , as they will give you more flexibility when reading back and forth.

Bearing in mind that you could just write FLAMESFLAMES as FLAMESSEMALF etc.

 int ctr = 10; List<Character> flames = Arrays.asList('F','L','A','M','E','S'); Iterator it = flames.iterator(); for(int z=0; z<ctr-1; z++) { if(!it.hasNext()) // if you are at the end of the list reset iterator it = flames.iterator(); System.out.println(it.next().toString()); // use the element } 

Out of curiosity, performing this cycle 1M times (average result of 100 samples) accepts:

  using modulo: 51ms using iterators: 95ms using guava cycle iterators: 453ms 

Edit: Loop iterators, as lbalazscs put it beautifully, are even more elegant. They come at a price, and the implementation of Guava is 4 times slower. You can execute your own implementation, tough.

 // guava example of cycle iterators Iterator<Character> iterator = Iterators.cycle(flames); for (int z = 0; z < ctr - 1; z++) { res = iterator.next(); } 
+6
source share

You should use % to make the index stay within flames.length so that they make a valid index

 int len = flames.length; for(int z = 0; z < ctr-1; z++){ res = (flames[z % len]); jLabel1.setText(String.valueOf(res)); } 
+5
source share

You can try the following: -

 char res; int ctr = 10 char[] flames = {'F','L','A','M','E','S'}; int n = flames.length(); for(int z = 0; z < ctr-1; z++){ res = flames[z %n]; jLabel1.setText(String.valueOf(res)); } 
+2
source share

Here is how I would do it:

 String flames = "FLAMES"; int ctr = 10; textLoop(flames.toCharArray(), jLabel1, ctr); 

TextLoop method:

 void textLoop(Iterable<Character> text, JLabel jLabel, int count){ int idx = 0; while(true) for(char ch: text){ jLabel.setText(String.valueOf(ch)); if(++idx < count) return; } } 

EDIT: An error was detected in the code ( idx , which must be initialized outside the loop). This has now been fixed. I also reorganized it into a separate function.

+1
source share

All Articles