如何使用随机类生成3个单词

问题描述 投票:0回答:2

我得到了一个讲述故事的多数组(基于随机选择的页面,段落和行号)。我需要生成一个密码,其中包含从数组中随机抽取的3个单词。必须给出创建密码的规则(例如:密码长度必须为10个字符,不得重复相同的单词);

这是用于Java。 (步骤1)密码必须由3个单词组成(步骤2),页面,段落和行号是随机选择的,并且必须使用random类通过nextInt()生成随机数。 (步骤3)使用split()分隔随机字符串中的每个单词。 (第4步)确保在第3步中从数组中选择一个随机词。(第5步)创建密码限制。

我为限制创建了if-else语句。如果未遵循规则,则程序必须始终返回到(步骤2)

 import java.util.Random;

 public class passGen {

   public static void main(String[] args) {

   Random r=new Random();

int pageNum = r.nextInt(story.length);
    int paraNum = r.nextInt(story.length);
    int lineNum = r.nextInt(story.length);

    System.out.print("Password = ");

    for (int i = 0; i<3; i++) {

        String sentence = story[pageNum][paraNum][lineNum]; // story is the array given
        String[] string = sentence.split(" ");  
        int index = new Random().nextInt(string.length);            
        String randomWord = string[index];

        if (randomWord.equals("a") || randomWord.contains("\n")) {
        }
        else 
            System.out.print(randomWord);

    }
      }
    }

假设随机发生器从数组中选择一个随机句子:story [0] [1] [5]给出“男孩正在骑自行车\ n”。使用split(),然后根据其索引随机选择单词,它会选择随机单词“ bicycle \ n”。我制定了一条规则,如果它选择一个带有换行符('\ n')的单词,则必须返回到再次生成随机数并给我一个新数组并找到一个新的随机单词直到找到一个新单词的步骤。没有\ n的单词。例如,假设故事[0] [1] [6]是“他很开心”。

我希望输出始终打印一个密码,并随机组合3个单词。

         password =  boyfun.having   // fun. is considered as one word with the period.

但是在某些情况下,如果失败,它只会打印出通过限制('\ n')的单词。有时它将打印1个单词或2个单词,或者在我运行程序时出现错误。

password = ridingfun

password = boy 

Password = Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Assign3Q1.main(passGen.java:123)

// line 123 happens is the String sentence = story[pageNum][paraNum][lineNum];
java arrays loops for-loop random
2个回答
0
投票

不是100%地确定您的意思,但是我很确定您最终会使用随机数生成器超出范围。

如果故事的长度为10,nextInt可以选择10,因为它包括您传递的int。因此,如果您最终得到10,然后执行story [10],则由于索引从0开始,您将越界。

我建议

r.nextInt(story.length - 1)

0
投票

我相信您的问题出在:

© www.soinside.com 2019 - 2024. All rights reserved.