1

I am learning how for loops work. I need to print the values

1a 2b 3c

This is what I have tried so far:

int [] numbers ={1, 2, 3};
String [] letters = {"a","b","c"};
for (int n: numbers){
    for( String l:letters){
        Log.i("sas","Result    " + n +l);
    }
}

This code is obviously not working. It gave me

1a 1b 1c 2a 2b 2c 3a 3b 3c

How can I fix the loop to give a result of 1a 2b 3c?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Mounir Elfassi
  • 2,242
  • 3
  • 23
  • 38

2 Answers2

4

You do not need two nested loops, you need one loop iterating both arrays at the same time:

for (int i = 0 ; i < Math.min(numbers.length, letters.length) ; i++) {
    Log.i("sas","Result    " + numbers[i] + letters[i]);
}

If you are certain that both arrays have the same number of elements, you could use length of one of them (i.e. numbers.length or letters.length, it does not matter since they are equal) for the stopping condition of your for loop.

Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1
for (int i = 0; i< numbers.length(); i++){
        Log.i("sas","Result    " + numbers[i] +letters[i]);
 }

Assuming that sizes of two arrays will be same and you want to attach corresponding items together

stinepike
  • 54,068
  • 14
  • 92
  • 112