简体   繁体   English

如何将数组中的 2 个单词添加到另一个数组中的字符串

[英]How to add 2 words from an array to a string from another array

I am writing a mad lib program for school.我正在为学校编写一个疯狂的 lib 程序。 The program must have 30 sentences, with two words from each sentence missing.该程序必须有 30 个句子,每个句子中缺少两个单词。 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.当使用 for 循环执行此操作时,它适用于第一句,但在之后的每个句子中都使用相同的单词。

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]); for (int i = 0; i < story.length; i++) { for (int j = i 2; j < (i 2)+1; j++) { story[i] = story[i].replaceFirst(placeholder,词[j]); // placeholder is set to '_' } System.out.println(story[i]); // 占位符设置为 '_' } 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.根据您的情况, words数组将包含 x2 个元素,而不是story数组。 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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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