how can i get an array to wrap around??

ex:

array String[] whatever = new String[3];

if i ask for the whatever[2] +1 I want it to give me 0 not 3
and if i ask whatever[0] - 1 i want it give me 2

Dani AI

Generated

The goal here is circular indexing: keep a fixed-size array and make any integer index map back into [0 .. length-1]. Several replies pointed toward that (notably for modulo), and the exception in your example came from trying to read an element before you wrapped the index. A few concrete points from the thread:

  • Arrays use the length property (not size()).
  • Do not call equals on an array element to test the index; check the index itself.
  • Normalize the index before using it to access the array to avoid ArrayIndexOutOfBoundsException.

A robust, concise approach is to compute a wrapped index and then index the array. In Java 8+ Math.floorMod handles negative values cleanly:

int len = arr.length;
int wrapped = Math.floorMod(candidateIndex, len);
String value = arr[wrapped];

If you are on an older Java version, use the common safe idiom that also handles negative indices:

int wrap(int index, int len) {
    return ((index % len) + len) % len;
}

Use that wrap(...) whenever you advance or retreat an index. For example, to step forward or backward from current by delta:

int next = wrap(current + delta, arr.length);

Troubleshooting tips grounded on the thread: normalize the index before any arr[...] access (that fixes the ArrayIndexOutOfBoundsException seen by ), prefer Math.floorMod for clarity, and remember ArrayList uses size() while arrays use length. For real circular buffers or concurrent producers/consumers, consider a dedicated circular buffer implementation instead of rolling your own index logic.

Recommended Answers

All 15 Replies

if(whatever[i+1] == whatever.size())
{
    i = 0;
}

"i" represent current position in array

i get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at dateapp.Main.main(Main.java:22)
Java Result: 1

public void test()
{
        String[]  j = new String[6];
        int i = 8;
        
       if(j[i+1].equals(j.length))
       {
            i = 0;
       }
       
       System.out.print(i);
    }

Use modulo arithmetic instead.

if ( i >= array.size() )
{
  i = i % array.size();
}

In fact, you don't even need the if-statement, just do the modulo...

i get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at dateapp.Main.main(Main.java:22)
Java Result: 1

public void test()
{
        String[]  j = new String[6];
        int i = 8;
        
       if(j[i+1].equals(j.length))
       {
            i = 0;
       }
       
       System.out.print(i);
    }

Your error was caused because i+1 does not EQUAL j.length, but is still greater than the bounds of the array. Also, you should probably use == to compare numbers, the equals method is used to compare objects.

using the modulus method above i get:

operator >= cannot be applied to int,Array.size

Sorry, array.length will serve you better where array is the name of your array.

i got it to work, but it only works 8 now = 0, but i want 9 to =1 and 10 to = 2 and so forth. so basically i want the array to go in a loop.

So what's your code? The modulo operator should handle that for you...

if(whatever[i+1] == whatever.size())
{
    i = 0;
}

"i" represent current position in array

Ohh sorry, my mistake. This happens when you tired and want to go sleep, but before that you decide to solve this last problem.

if(i+1 == whatever.size())
{
    i = 0;
}
else if(i-1 > 0)
{
    i = whatever.size() -1;
}

you you need only current position in array "i" compared to array size or zero value

i got it to work, but it only works 8 now = 0, but i want 9 to =1 and 10 to = 2 and so forth. so basically i want the array to go in a loop.

darkagn is correct. If you're using the mod operator correctly then that is exactly the behavior you should get.

private int x = 8;
private int y =0;
while(x<array.length){

array[x]=y;

x++;
y++;
}

let me know if that is what your looking for

No, that is nothing like what he is looking for at all.

No, that is nothing like what he is looking for at all.

how he wantz element 8 in the array to equal 0 and 9=1 10=2 11=3 etc and thatz what that peice of coding i wrote does

No, he wants the index to wrap back around in a loop against a fixed-size array. A circular array iteration is what he is asking about.

Your code merely alters the elements [8] through [length-1] to count up from zero until the end of the array.

No, he wants the index to wrap back around in a loop against a fixed-size array. A circular array iteration is what he is asking about.

Your code merely alters the elements [8] through [length-1] to count up from zero until the end of the array.

okay i see sorry

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.