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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you man, that what i need, i have to wait 10 min to accept your answer.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.