manbearpiig
manbearpiig

Reputation: 65

String array looping out multipe text

In the same main, create an array of 10 strings. Using nested loops, fill it with values so that each element is a string containing a number of x's based on the index, so the 0th element is "", the 1st element is "x" the 2nd element is "xx", and the 9th element is "xxxxxxxxx". (hint, one loop will move you through the array, the other will add the right number of x's to the current element).

No idea how to do this....

Upvotes: 0

Views: 68

Answers (1)

EDToaster
EDToaster

Reputation: 3180

First of all, you need to start with the logic of the program

You need to start with the main method

public static void main(String[] args){

Then you need to define an array of Strings

String[] array = new String[10]; //creates an array of size ten

Next, you need to think about the loop. The first loop you need is the loop through the indexes and elements of the array. Using for loop

for(int i=0;i<array.length();i++){

This executes the contents within 10 times. Next you need to use a StringBuilder to append each 'x'

StringBuilder string =new StringBuilder();

Next you need to loop (using for) through the value of i

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

Then append string

string.append("x");

After the 2nd for loop, populate the array at index i

array[i]= string.toString();

Then you are done! The variable array is what you need

public static void main(String[] args){

     String[] array = new String[10]; //creates an array of size ten
     for(int i=0;i<array.length();i++){
         StringBuilder string =new StringBuilder();
          for(int x=0;x<i;x++)
               string.append("x");
          array[i]= string.toString();
     }
 }

Without StringBuilder

public static void main(String[] args){

     String[] array = new String[10]; //creates an array of size ten
     for(int i=0;i<array.length();i++){
         String string ="";
          for(int x=0;x<i;x++)
               string += "x";
          array[i]= string;
     }
 }

Upvotes: 1

Related Questions