How to print array five times with loop?

3675 views java
-1

I need to write different methods for printing phrases with loops and I'm having trouble with printing an array. My assignment is to have each method print the phrase 5 times but I can't figure out how to do it with the array. This is what I have so far and it only prints once.

  String[] words = {"I'm ","Ready ","Now!"};
  for(int i=0; i < 5; i++)
  {
  System.out.print(words[i]);
  }

answered question

One loop to count from 1 to 5, another inner one to count from 0 to the last element of the array.

You could use nested loops, the outer for loop to tell it to run 5 times, and the inner one which is the loop you already created inside. That would do it 5 times. But you would want to change your current loops I < 5 to I < arraylength - 1.

I'm pretty sure this will throw an ArrayOutOfBoundsException

1 Answer

7

My assignment is to have each method print the phrase 5 times but I can't figure out how to do it with the array.

Use nested for loop and beware of array size.

String[] words = {"I'm ","Ready ","Now!"};
  for(int i=0; i < 3; i++) //<----use proper size
  {
    for(int j=0;j<5;j++)  //<---print each word 5 times
      {System.out.print(words[i]);}
  }

posted this

Have an answer?

JD

Please login first before posting an answer.