Java编程:数组和随机数

时间:2013-04-16 00:03:45

标签: java arrays random

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

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

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

3 个答案:

答案 0 :(得分:0)

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

即。

之类的东西
while (true) {
     int i = gen.nextInt(10);
     System.out.println("foo " + i);
}

答案 1 :(得分:0)

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

答案 2 :(得分: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 */
}