Home > Software design >  How to add 2 words from an array to a string from another array
How to add 2 words from an array to a string from another array

Time:12-10

I am writing a mad lib program for school. The program must have 30 sentences, with two words from each sentence missing. I planned to store the sentences in an array, user-inputted words in a second array, and then add words from the word array to the sentences in the sentence array. When using for loops to do this, it works for the first sentence, but in every sentence after that the the same words are used.

Here's the code I have for this part:

String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};

String words[] = {"awesome", "James", "checkers", "Sunday"};

for (int i = 0; i < story.length; i  ) { 
    for (int j = 0; j < words.length; j  ) { 
        story[i] = story[i].replaceFirst(placeholder, words[j]); // placeholder is set to '_'
    }
System.out.println(story[i]); 
}

CodePudding user response:

This should work

    String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};
    String words[] = {"awesome", "James", "checkers", "Sunday"};
    int j=0;
    for (int i = 0; i < story.length; i  ) {
        while(story[i].contains("_")){
            story[i] = story[i].replaceFirst("_", words[j  ]);
        }
        System.out.println(story[i]);
    }

CodePudding user response:

According to your case the words array will contain x2 elements more than story array. We can use that to write a simple algorithm:

String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};
String words[] = {"awesome", "James", "checkers", "Sunday"};
String placeholder = "_";
for (int i = 0; i < story.length; i  ) {
    String word1 = words[i * 2];
    String word2 = words[i * 2   1];
    story[i] = story[i]
            .replaceFirst(placeholder, word1)
            .replaceFirst(placeholder, word2);

    System.out.println(story[i]);
}

CodePudding user response:

This would work if you really solve it with this way:

for (int i = 0; i < story.length; i  ) { 
    for (int j = i*2; j < (i*2) 1; j  ) { 
        story[i] = story[i].replaceFirst(placeholder, words[j]); // placeholder is set to '_'
    }
    System.out.println(story[i]); 
}
  • Related