-1

我有一个任务是创建一个生成随机“诗歌”的程序。这是我的代码:

package poem;

import java.util.Random;


public class Poem {

    public static void main(String[] args) {
        String rhyme1[] = {"ball", "call", "mall", "hall", "guy named Paul"};
        String rhyme2[] = {"cat","hat", "bat", "rat", "mat", "guy named Pat"};
        String nouns[] = {"you", "I", "girl", "boy", "man", "woman"};
        String verbs[] = {"run", "jump", "dive", "sink", "fall", "collapse", "swim", "love"};
        String others[] = {"like a", "into a", "nothing like a"};

        Random gen = new Random();

        String currentNoun = nouns[gen.nextInt(nouns.length)];
        String currentVerb = verbs[gen.nextInt(verbs.length)];
        String currentRhyme1 = rhyme1[gen.nextInt(rhyme1.length)];
        String currentRhyme2 = rhyme2[gen.nextInt(rhyme2.length)];
        String currentOther = others[gen.nextInt(others.length)];

        System.out.printf("%s %s %s %s \n", currentNoun, currentVerb, currentOther, currentRhyme1);
        System.out.printf("%s %s %s %s \n", currentNoun, currentVerb, currentOther, currentRhyme1);}}

我的问题是,当我运行它时,我两次都得到完全相同的行。如何每次获得不同的随机生成的行?提前致谢。

4

3 回答 3

0

问题是每个变量只调用一次 gen.nextInt 。当您生成随机数并将其分配给 currentX 时,这是您分配它的唯一时间。您应该将字符串赋值和 sysout 放在一个循环中,以生成新的随机值并打印它们。

即类似的东西

while (true) {
     int i = gen.nextInt(10);
     System.out.println("foo " + i);
}
于 2013-04-16T00:07:49.407 回答
0

您分配currentNoun,currentVerb等一次,然后将它们打印两次。除非您在再次打印之前重新分配它们,否则它们的值不会改变。

于 2013-04-16T00:09:49.197 回答
0

从你第一次调用到第二次,变量没有改变System.out.printf(),所以你只是打印了两次。一种解决方法是创建一个 generatePoems 方法,该方法将打印任意数量的诗歌,然后从 main 方法调用它。这样一来,整个事情就会更干净,代码也相对可重用。

void generatePoems(int numberOfPoems){ //This block should be outside of the main method
  for (int i = 0; i<numberOfPoems;i++){

  String rhyme1[] = {"ball", "call", "mall", "hall", "guy named Paul"};
  String rhyme2[] = {"cat","hat", "bat", "rat", "mat", "guy named Pat"};
  String nouns[] = {"you", "I", "girl", "boy", "man", "woman"};
  String verbs[] = {"run", "jump", "dive", "sink", "fall", "collapse", "swim", "love"};
  String others[] = {"like a", "into a", "nothing like a"};

  Random gen = new Random();

  String currentNoun = nouns[gen.nextInt(nouns.length)];
  String currentVerb = verbs[gen.nextInt(verbs.length)];
  String currentRhyme1 = rhyme1[gen.nextInt(rhyme1.length)];
  String currentRhyme2 = rhyme2[gen.nextInt(rhyme2.length)];
  String currentOther = others[gen.nextInt(others.length)];
  System.out.printf("%s %s %s %s \n", currentNoun, currentVerb, currentOther, currentRhyme1);
  }
}

您的主要方法应如下所示:

public static void main(String[] args) {
  generatePoems(2);
  /* 2 is the number of poems you want to generate. Can be anything as long as its
  under 2147483647 */
}
于 2013-04-16T00:11:42.570 回答