简体   繁体   中英

How to add 2 words from an array to a string from another array

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]); 
}

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]); }

i guess this would work if you really wanna solve it this way

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]);
    }

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM