user3872094
user3872094

Reputation: 3351

unable to understand how to loop in loop

I'm writing a java code to loop the data and inside it there is another loop. Below is my code.

String names[] = { "user1", "User2", "User3", "User4", "User5" };
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < names.length; j++) {
        System.out.println(i + " " + names[j]);
    }
}

Thre output that i get is as below, i.e. for each i the user names are getting printed, but i want them to be printed in a series if i values. please see the expected output for better understanding.

Current output:

0 user1
0 User2
0 User3
0 User4
0 User5
1 user1
1 User2
1 User3
1 User4
1 User5
2 user1
2 User2
2 User3
2 User4
2 User5
3 user1
3 User2
3 User3
3 User4
3 User5
4 user1
4 User2
4 User3
4 User4
4 User5
5 user1
5 User2
5 User3
5 User4
5 User5
6 user1
6 User2
6 User3
6 User4
6 User5
7 user1
7 User2
7 User3
7 User4
7 User5
8 user1
8 User2
8 User3
8 User4
8 User5
9 user1
9 User2
9 User3
9 User4
9 User5

Expected output:

0 user1
1 User2
2 User3
3 User4
4 User5
5 user1
6 User2
7 User3
8 User4
9 User5

please let me know how can i achieve this.

Upvotes: 2

Views: 101

Answers (3)

Sajan Chandran
Sajan Chandran

Reputation: 11487

Using Java 8

    String names[] = { "user1", "User2", "User3", "User4", "User5" };
    IntStream.range(0, 10).forEach( i -> System.out.println(i + " " + names[i % names.length]));

Upvotes: 0

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22224

You can do it with a single for loop :

for (int i = 0; i < 10 * names.length; i++) {
    System.out.println(i + " " + names[i % names.length]);
}

With this statement i % names.length you would be using the array as ring-buffer. So when you increment i just beyond the length of the array the result of modulo would be 0 and it would continue from there. Which seems to be what you want.

This will print 50 lines as a result, up to 49 User5. If you want 10 lines for example just put this limit as terminating condition in the for loop.

for (int i = 0; i < 10; i++)

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

This is a good opportunity to learn about the mod operator %:

for (int i = 0; j < 10 ; i++) {
    System.out.println(i + " " + names[i % names.length]);
}

The operator produces the remainder of the division of its left operand (in this case, it's i) by its right operand, names.length, i.e. by 5. As i increases from zero to ten, the series of remainders of division by 5 proceeds as follows:

0 1 2 3 4 0 1 2 3 4

This is a common way to cycle your index back to the beginning of an array without making a separate counter for it.

Upvotes: 2

Related Questions