ARP
ARP

Reputation: 613

Looping one array with another array in Java

I have two arrays

1) String[] images = {"#1","#2", "#3", "#4", "#5" };

2) String[] items = {"1","2", "3", "4", "5", "6", "7", "8" };

The Items may vary , but the images array is fixed. I wan the output mapping like

 image 1 => item 1
 image 2 => item 2 
 image 3 => item 3
 image 4 => item 4
 image 5 => item 5
 image 1 => item 6
 image 2 => item 7
 image 3 => item 8

and so on. My work around is as follows,

public static void main(String[] args) {
            for( int y=0;y< items.length;y++ ){
            for( int i=0;i< images.length;i++ ){

                if( y >= images.length ){
                    int remaining = items.length % images.length;
                    System.out.println("remaining..." + remaining);
                    for( int x=0;x<=remaining;x++ ){
                        System.out.println( "image" +images[x]+"=> item =>"+items[x]);
                    }
                    return;
                }
                System.out.println( "image" +images[y]+"=> item =>"+items[y]);
                break;
            }
        }
    }

Upvotes: 1

Views: 589

Answers (1)

AntonH
AntonH

Reputation: 6437

Try this code:

for (int i=0 ; i<items.length ; i++) {
    System.out.println(images[i%images.length] + " => " + items[i]);
}

i%images.length gives the rest of the division of i, i.e. your position in the items array, with the length of the images array. So images[i%images.length] loops through the images array.

Upvotes: 6

Related Questions