0

So I want the result to be "Today Blue" and "Tomorrow Red" how can I do that by looping?

String[] sections = 
        {
          "Blue",
          "Red"
        };

       String[] stringDay = 
        {
          "Today",
          "Tomorrow"
        };

    for(String sectionsLoop : sections)
    {
        System.out.println(stringDay + " " + sectionsLoop);
    }
6
  • Use an old loop. Commented Mar 10, 2020 at 5:22
  • You an index in the loop: for(int i = 0; i < Math.min(sections.length, stringNumber.length); i++) Commented Mar 10, 2020 at 5:22
  • HI there sorry, I explained wrong, I edited my question Commented Mar 10, 2020 at 5:25
  • 1
    for (int i = 0; i < sections.length && i < stringDay.length; i++) { System.out.println(stringDay[i] + " " + sections[i]); } Commented Mar 10, 2020 at 5:47
  • 1
    Does this answer your question? Iterating over two arrays simultaneously using for each loop in Java Commented Mar 10, 2020 at 7:28

2 Answers 2

1
public static void main(String... args) {

  String[] selection =  new String[] {"Blue","red"};
  String[] day = new String[] {"today","tomorrow"};

  for(int i = 0 ; i < s.length ; ++i) {
      System.out.println(day[i] + " " + selection[i]);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great this worked thanks!!
0

You can use the traditional for loop but you have to make sure both arrays from the same size or do the below to prevent arrayOutOfIndex

    int size = sections.length > stringNumber.length ?sections.length : stringNumber.length;
    for (int i = 0; i <size ; i++) {
        if (sections.length < i) {
            System.out.println(sections[i]);
        }
        if (stringNumber.length < i) {
            System.out.println(stringNumber[i]);
        }
    }

1 Comment

You need to update your answer..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.